Execution doesn't stop when you call then
on a Promise
like it does when you use await
. On the first loop a Promise
is created whose then
method will execute in one second, but the function continues looping because execution hasn't stopped. At the end of the loop you have five Promise
objects that have all been created consecutively with no pauses in between, so their one-second timeouts all execute very close to one another.
Here's the await
method with a comment calling out where execution stops.
function wait(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
async function countDown(count) {
for (let i = count; i > 0; i--) {
await wait(1000); // Execution stops here for one second before continuing
console.log(i);
}
}
countDown(5);
Here's something closer to Phúc Đỗ Vương's answer with a comment calling out where execution doesn't stop.
function wait(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
function countDown(count) {
if (count === 0) {
return;
}
wait(1000).then(() => {
// This code, including the next call to countDown, will execute in one second
console.log(count);
countDown(count - 1);
});
// The current call to countDown finishes before the next call begins
}
countDown(5);