【问题标题】:How to get asynchronous data from an object's `get()` without returning a Promise如何在不返回 Promise 的情况下从对象的`get()` 获取异步数据
【发布时间】:2019-07-19 18:16:25
【问题描述】:

在 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 解决?怎么样?

【问题讨论】:

  • 只是出于好奇,您为什么需要它来制作异步函数?您是从数据库还是从 http 调用中读取该值?
  • 使用 async/await 不会真正帮助你。它将删除.then,但是您每次都需要像这样获取您的财产:await scope.word。这似乎更容易,但您还必须记住,为了使用await,它必须在async 函数中使用。像这样:jsfiddle.net/v7ohbsfx
  • async/await 只是一个语法糖。类似于async function yourFunction() { var word = await scope.word; }
  • 这个问题也解决了同样的要求。stackoverflow.com/questions/11843619/…
  • 没有。如果不致电 CB 或 await,您将无法获得返回的承诺。

标签: javascript asynchronous async-await getter-setter defineproperty


【解决方案1】:

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

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

    scope.word(res=>console.log(res))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2018-05-28
    • 2019-10-27
    • 2018-07-15
    • 2023-03-08
    相关资源
    最近更新 更多