Async Function in Getter w/ Return in Callback

Viewed 5137

I want to define a read-only object property that asynchronously fetches a value and then returns it using the new EcmaScript 5 getters.

However, the property always returns undefined even though magicValue in the example code below is definitively never undefined. Also, when I just return 'xxx'; the printed value is still undefined. It only works when I return outside the callback function.

It seems like return is being executed immediately regardless of whether the callback of myAsyncFunction is called. I am not sure whether this a bug in in V8 or if I am abusing JavaScript's getters.
Can I get this to work? I thought, since I can use getters and setters now, I will use getters/setters to read and write properties and regular functions to do certain tasks.

var User = function (id) {
    this.id = id;
};

Object.defineProperty(User.prototype, 'magic', {
    get : function () {
        myAsyncFunction(function (magicValue) {
            return magicValue;
        });
    }
});

var u = new User(5);
console.log(u.magic);

Prints undefined.

3 Answers
Related