有了Promise,我可以拥有两个独立的"线程"两者都在等待相同的值:
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复制它,但无济于事。
以下代码段不起作用:
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?
&#13;
是否可以使用async / await?
在第一个代码段中编写相同的功能如果需要,我可以回到使用Promise。
答案 0 :(得分:2)
要await
,您需要引用单数承诺,因此您无法按需调用函数并让该函数创建承诺,然后在其他地方使用相同的承诺(除非创建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);
&#13;
不要仅仅使用async
来返回一个承诺 - 如果函数的目的是创建一个承诺,那么明确地做 - 这样,它更清楚是什么你的代码是有意义的。 Async和await 没有使Promise关键字过时,它只是语法糖,在某些情况下很有用(在其他情况下是不必要的)。