使用 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');
以下代码片段无法工作:
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?
使用async/await,能否编写与第一个片段相同的功能?
如果需要,我可以回退到使用Promise。
async function as1
和async function as2
,该工具将Promise作为参数,并返回一个等待Promise的函数。这样所有重复的逻辑都在一个地方了。我想我会这么做。 - Joe Frambach