Reputation: 1334
I wonder why in the below code the first console log prints 0. The second does print 1oo as expected. Can someone explain?
let count = 0;
async function incr(): Promise<number> {
setTimeout(() => count++, 1);
return count;
}
const promises = [];
for (let i = 0; i < 100; i++) promises.push(incr());
Promise.all(promises).then(async () => console.log('count = ' + count));
setTimeout(() => {
console.log('count = ' + count);
}, 100);
Upvotes: 0
Views: 40
Reputation: 370659
Your incr
function doesn't return anything explicitly, so it returns a Promise that resolves immediately.
Promise.all
runs in the microtask queue as soon as all Promises in the passed array resolve. So, that's what runs first - the callback passed to Promise.all(promises).then(
.
The setTimeout
queues a macrotask, and such tasks run much later than microtasks.
If you wanted it to log 100, do:
let count = 0;
function incr() {
return new Promise((resolve) => {
setTimeout(() => {
count++;
resolve();
}, 1);
});
}
const promises = [];
for (let i = 0; i < 100; i++) promises.push(incr());
Promise.all(promises).then(async() => console.log('count = ' + count));
setTimeout(() => {
console.log('count = ' + count);
}, 100);
Upvotes: 1