【问题标题】:Read Async Object Set Using Await使用 Await 读取异步对象集
【发布时间】:2020-02-11 11:53:07
【问题描述】:

全局对象的键/值 (thing) 使用 await 在异步函数 setter(); 中设置。如何在另一个异步函数getter();中异步读取thing的值?

我收到未定义的错误,因为 getter();setter(); 中的 await 完成之前运行。

let obj = {};

async function af() {
    return 1;
}

(async function setter () {
  obj.thing = await af();
})();

(async function getter () {
  let thing = obj.thing;
})();

【问题讨论】:

    标签: javascript async-await ecmascript-2017


    【解决方案1】:

    您应该等待 setter 函数完成,您会遇到这种方法的竞争条件问题。

    一个如何工作的例子是:

    var obj = {};
    
    async function af() {
        return 1;
    }
    
    (async function() {
        await (async function setter () {
          obj.thing = await af();
        })();
    
        await (async function getter () {
          let thing = obj.thing;
        })();
    
        console.log(obj.thing);
    })();
    

    在函数结束时,它应该记录 af 函数返回的 1

    【讨论】:

      猜你喜欢
      • 2013-09-19
      • 1970-01-01
      • 2018-07-24
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 2014-10-11
      • 2016-12-04
      相关资源
      最近更新 更多