问题
I have the following code:
var incr = num => new Promise(resolve => {
resolve(num + 1);
});
var x = incr(3)
.then(resp => incr(resp))
.then(resp => console.log(resp));
async function incrTwice(num) {
const first = await incr(num);
const twice = await incr(first);
console.log(twice);
}
incrTwice(6);
Which I believe (perhaps mistakenly) shows two equivalent ways to achieve the same functionality: first by chaining promises and second with the syntactic sugar of async/await.
I would expect the promise chaining solution to console.log first, then the async function second, however the async function console.log's first then the promise chaining solution prints.
My logic is as follows:
x
s initial resolve would be first on the microtask queue as the declaration is processed- the stack is empty between the declaration of
x
andincrTwice
which would cause the microtask queue to be flushed (resulting in the completion of the promise chain)- x prints first
incrTwice
is definedincrTwice
executes queueing on the microtask queue at theawait
s eventually printing to the console- incrTwice prints second
Clearly I have a misunderstanding somewhere, is someone able to point out where I am wrong?
回答1:
First of all, let me point out that you never should argue about the execution order of independent promise chains. There are two asynchronous calls, and they do not depend on each other but run concurrently, so they should always be expected to finish in arbitrary order.
Toy examples that only use immediately-resolving promises make this order depend on microtask queueing semantics instead of actual asynchronous tasks, which makes this a purely academic exercise (whose result is subject to changes in the spec).
Anyway, let's clear up your misunderstandings:
the stack is empty between the declaration of
x
andincrTwice
which would cause the microtask queue to be flushed
No, the stack only becomes empty after all user code is ran to completion. There's still the global execution context of the <script>
element on the stack. No microtasks are executed until all synchronous code (incr = …
, x = incr(3).…
and incrTwice(6)
) has finished.
I believe [the code] shows two equivalent ways to achieve the same functionality: first by chaining promises and second with the syntactic sugar of async/await.
Not exactly. The .then()
chaining has an additional resolve step when unnesting the incr(resp)
promise that is returned from the first .then(…)
handler. To make it behave precisely the same as the await
ed promises in incrTwice
, you'd need to write
incr(3).then(resp =>
incr(resp).then(resp =>
console.log(resp)
)
);
If you do that, you'll actually get the console
logs in the order in which you started the two promise chains because they will take the same number of microtasks until the console.log()
is executed.
For more details, see What is the order of execution in javascript promises, Resolve order of Promises within Promises, What happen when we return a value and when we return a Promise.resolve from a then() chain, in the microtask queue?, What is the difference between returned Promise?, ES6 promise execution order for returned values
回答2:
Your thinking is understandable and logical. The reason for the observed behaviour has to do with one of the guarantees that were built into the Promise API, namely that promises are always asynchronous in execution, even if they carry out synchronous operations (like resolving the promise immediately). More technically, this means a promise's callback will never be called until the current run has completed.
As MDN puts it:
Callbacks will never be called before the completion of the current run of the JavaScript event loop.
So:
Promise.resolve(10).then(value => console.log(value));
console.log(20); //20, 10 - NOT 10, 20
I cover this in my guide to promises which can be found here.
来源:https://stackoverflow.com/questions/62405525/why-does-this-async-function-execute-before-the-equivalent-promise-then-chain-de