如何从对象的`get()`获取异步数据而不返回Promise

问题描述 投票:2回答:1

在NodeJS中,我有一个像这样的对象,

var scope = { word: "init" };

使用Object.defineProperty as described in MDN我重写get()函数是这样的,

Object.defineProperty(scope, 'word', {
  get: function() {
    return Math.random();
  }
});

每当我在控制台中使用scope.word时,它会正确返回一个新的随机数。但是,该函数还必须从具有回调函数获取数据。所以它的工作方式非常像setTimeout

Object.defineProperty(scope, 'word', {
  get: function() {
    setTimeout(() => {
      return Math.random();
    }, 1000)
  }
});

现在每次我做scope.word我得到,

未定义

因为get()函数是同步的。这当然可以通过返回Promise来解决,

Object.defineProperty(scope, 'word', {
  get: function() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(Math.random());
      }, 1000)
    });
  }
});

但后来我需要做scope.word.then(...),但我们正在构建的背后的整个想法是开发人员只需要scope.word就好像它是一个简单易用的变量。就像Angular的$ scope或VUE.js'数据'一样。

如何让get()函数返回实际值,而不是Promise?是否有可能使用async / await解决方法?怎么样?

javascript asynchronous async-await getter-setter defineproperty
1个回答
-1
投票

其中一个解决方案就是像这样传递回调函数。

    const scope = {}
    Object.defineProperty(scope, 'word', {
      value: (cb)=>{
      	  setTimeout(() => {
              cb(Math.random())
          }, 1000)
      }
    });

    scope.word(res=>console.log(res))
© www.soinside.com 2019 - 2024. All rights reserved.