带回调的Getter中的异步函数 [英] Async Function in Getter w/ Return in Callback

查看:265
本文介绍了带回调的Getter中的异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个只读对象属性,该属性异步获取一个值,然后使用新的EcmaScript 5 getter返回它。

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

但是,该属性总是返回即使以下示例代码中的 magicValue 绝对不是未定义的,但未定义。另外,当我只是返回 xxx; 时,打印的值仍然是 undefined 。仅当我 return 在回调函数之外时才起作用。

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.

似乎 return 会立即执行,无论是否调用 myAsyncFunction 的回调。
我不确定这是V8中的错误还是滥用JavaScript的吸气剂。

我可以使它正常工作吗?我想,因为现在可以使用getter和setter了,所以我将使用getters / setter读取和写入属性和常规函数来完成某些任务。

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);

打印未定义

推荐答案

如今,异步操作通常由承诺。调用getter时,它将返回一个promise,您可以使用'then()'方法附加一个回调。

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);
    });
  }
});

下面是一个工作示例:
https://jsfiddle.net/tw6gaudz/2/

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

这篇关于带回调的Getter中的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆