I want to define a property of a read-only object that asynchronously retrieves a value and then returns it using the new EcmaScript 5 getters.
However, the property always returns undefined , although magicValue in the example below code is never finally undefined. Also, when I just return 'xxx'; , the printed value remains undefined . It only works when I return outside the callback function.
It seems that return is executed immediately, regardless of whether the myAsyncFunction callback is called. I'm not sure if this is a bug in V8 or if I abuse JavaScript recipients.
Can I make this work? I thought, since now I can use getters and setters, I will use getters / setters to read and write properties and regular functions to perform 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);
Printing is undefined .
source share