Async function in Getter w / Return in callback

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 .

+6
source share
3 answers

Asynchronous operations, at present, are usually handled using Promises . When you call your recipient, it returns a promise to which you can attach a callback using the "then ()" method.

 Object.defineProperty(User.prototype, "magic", { get: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(JSON.stringify({ magic: 'value' })); }, 1000); }); } }); 

Here is a working example: https://jsfiddle.net/tw6gaudz/2/

+3
source

Thanks @utkanos for your help.

JavaScript will not return the getter function asynchronously because getters are synchronous.

+3
source

You can use the "setter":

 var User = function (id) { this.id = id; }; Object.defineProperty(User.prototype, 'magic', { set : function (value) { setTimeout(value.bind(0, "hello"), 1000); return true; } }); var a = new User(5); a.magic = function(msg){ alert(msg); }; 
0
source

Source: https://habr.com/ru/post/922269/


All Articles