简短的答案是,就每个案例而言,你重新建立了3个短期的允诺链,而随着下降,你又重新建立了1个长期复杂链。 但是,让我们一步步地看待这一问题。
const promises = [
new Promise(r => setTimeout(r, 10000, "Hi")),
new Promise(r => setTimeout(r, 500, "second")),
new Promise(r => setTimeout(r, 100, "third"))
];
First, I ll point out that these lines of code start the timeouts immediately. So regardless of what happens later, the timers will always go off at the 100ms, 500ms, and 10000ms marks (plus or minus the usual innacuracy of timers). The await
s decide what you want to pause for, but they don t affect when the original 3 promises resolve.
考虑到这一点,请看每一案件,因为它最简单。 我拿走了<代码>await 3,因为那很少。
promises.forEach(async promise => {
const p = await promise;
console.log(p);
});
Your function first gets called with the 10000ms promise. You await the 10000 ms promise, which causes your function to return a promise of its own. .forEach
doesn t care what you return, so it moves on to the next element in the array, which is the 500ms promise. You await the 500 ms promise and return. Then same thing with the 100ms promise.
在100万ms之后,这一原始承诺将得到解决。 这意味着,现在可以恢复你职责的第三例,排出第三例。 在500米的标志上,这一最初的允诺决定了,使第二功能得以恢复。 最后,在10 000个标识上,这一功能的一审可以恢复。
And now let s turn our attention to the reducer case.
promises.reduce(async (a, promise) => {
await a;
const p = await promise;
console.log(p);
}, Promise.resolve());
关于第一个版本,a
是Promise.resolve(<>/code>和promise<>的许诺。 您正在等待<条码>a条码>,使您得以恢复新的承诺。 我们现在进入第二代。 <代码>a
为首版的允诺,promise
为500姆斯许诺。 您正在等待<条码>a>。 我们现在进入第三份版本,其中a
是第二版的许诺,promise
是100ms许诺。 您正在等待<代码>a
,并兑现承诺。
Now that we ve finished the synchronous code, a microtask gets queued and the first function resumes after it s await a
. The first function moves on to the next line and await
s promise
, which is the 10000ms promise. The function pauses execution at this point.
A bit later, the 100ms promise resolves. Nothing is directly awaiting it, so nothing happens at this point. Later still, the 500ms promise resolves. Again, nothing is directly awaiting it. And even later, the 10000ms promise resolves. This allows the first function to resume. It logs "hi", then returns, thus resolving its own promise. Because it resolved its promise, function 2 (which was patiently sitting on await a
) can now resume. function 2 then awaits promise
, which is the 500ms promise. This promise is already resolved, so after the briefest of interruptions it resumes, logs "second" and returns. This in turn unlocks function 3, which awaits promise
(the 100ms one), then resumes. It logs out "third" and is done.