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?