【问题标题】:Wait for async function in multiple places在多个地方等待异步功能
【发布时间】:2018-09-10 01:53:50
【问题描述】:

有了 Promises,我可以有两个单独的“线程”都在等待相同的值:

let trigger;
const promise = new Promise(r => {
  console.log('promise is created *once*');
  trigger = value => {
    console.log('trigger is called *once*');
    r(value);
  }
});

(async () => {
  console.log('A waiting');
  const value = await promise;
  console.log(`A finished, got ${value}`);
})();

(async () => {
  console.log('B waiting');
  const value = await promise;
  console.log(`B finished, got ${value}`);
})();

trigger('hello');
console.log('And *two* things are waiting on the single promise');

我尝试使用 async/await 复制此内容,但无济于事。

下面的sn-p不起作用:

let trigger = async () => {
  console.log('trigger should be called *once*');
  return 'hello';
};

(async () => {
  console.log('A waiting');
  const value = await trigger; // <-- What do I need to put here?
  console.log(`A finished, got ${value}`);
})();

(async () => {
  console.log('B waiting');
  const value = await trigger; // <-- What do I need to put here?
  console.log(`B finished, got ${value}`);
})();

trigger(); // <-- How can this "kick off" the two awaits above?

是否可以在第一个 sn-p 中使用 async/await 编写相同的功能?

如果需要,我可以退回使用 Promise。

【问题讨论】:

    标签: javascript async-await es6-promise


    【解决方案1】:

    对于await,您需要引用单数承诺,因此您不能按需调用函数并让该函数创建承诺,然后在其他地方使用相同的承诺(除非创建promise 也将其保持在状态以返回给其他调用者,例如单例)。

    我最初会创建一个单一的 Promise,然后将其发送到异步函数:

    const trigger = async () => {
      console.log('trigger should be called *once*');
      return 'hello';
    };
    
    async function as1(prom) {
      console.log('A waiting');
      const value = await prom;
      console.log(`A finished, got ${value}`);
    }
    
    async function as2(prom) {
      console.log('B waiting');
      const value = await prom;
      console.log(`B finished, got ${value}`);
    }
    
    const thePromise = trigger();
    as1(thePromise);
    as2(thePromise);

    不要使用async 来返回一个promise,但是——如果一个函数的目的是创建一个promise,那么明确地执行它——这样,你的代码的意图就更清楚了。 Async 和 await 并没有使 Promise 关键字过时,它只是语法糖,在某些情况下很有用(而在其他情况下则不必要)。

    【讨论】:

    • 哈哈。这就说得通了。我可以用一个实用程序包装async function as1async function as2,该实用程序将promise 作为参数,并返回一个等待我的promise 的函数。所以所有重复的逻辑都在一个地方。我想我会这样做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2021-08-23
    • 1970-01-01
    • 2019-04-22
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多