【发布时间】: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