Fra*_*bot 4 javascript async-await es6-promise
使用 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');
Run Code Online (Sandbox Code Playgroud)
我试图用 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?
Run Code Online (Sandbox Code Playgroud)
是否可以使用 async/await 在第一个代码段中编写相同的功能?
如果需要,我可以重新使用 Promise。
To await
,您需要引用单个承诺,因此您不能按需调用函数并让该函数创建一个承诺,然后在其他地方使用相同的承诺(除非创建该承诺的函数也将其保持在状态返回给其他调用者,如单身人士)。
我最初会创建一个单一的承诺,然后将其发送到异步函数:
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);
Run Code Online (Sandbox Code Playgroud)
但是,不要async
仅用于返回承诺 - 如果函数的目的是创建承诺,那么明确地执行 - 这样,您的代码打算做什么就更清楚了。Async 和 await并没有使 Promise 关键字过时,它只是语法糖,在某些情况下很有用(而在其他情况下则不必要)。