代码之家  ›  专栏  ›  技术社区  ›  adelriosantiago

如何在不返回承诺的情况下从对象的“get()”获取异步数据

  •  1
  • adelriosantiago  · 技术社区  · 6 年前

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

    现在每次我这么做 范围.word

    未定义

    因为 获取() 函数是同步的。这当然可以通过回复承诺来解决,

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

    但我需要做的是 scope.word.then(...) 但我们正在构建的整个概念是,开发人员只需 范围.word 就像是一个简单易用的变量。 就像一个角度的$范围或虚拟用户.js'数据' .

    我怎么才能做这个 函数返回实际值,而不是承诺?是否可以使用 async await

    1 回复  |  直到 6 年前
        1
  •  -1
  •   DedaDev    6 年前

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

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