Async Function in Getter w/ Return in Callback

末鹿安然 提交于 2019-12-08 19:28:44

问题


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.


回答1:


Asynchronous operations, these days, are typically handled with Promises. When you invoke your getter, it returns a promise, which you can attach a callback with 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/




回答2:


Thanks @utkanos for your help.

JavaScript won't acynchronously return a getter function's value because getters are synchronous.




回答3:


You could use a "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);
};


来源:https://stackoverflow.com/questions/11843619/async-function-in-getter-w-return-in-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!