Search⌘ K
AI Features

Solution Review: Print Numbers Sequentially

Explore how to print numbers in sequential order in JavaScript despite varying asynchronous delays. Understand the use of async functions and the await keyword to ensure promises resolve one after another. This lesson helps you master controlling asynchronous execution flow with callbacks and promises.

We'll cover the following...

Solution

Node.js
const sleep = (i,ms) => new Promise(resolve => setTimeout(() => resolve(i), ms));
async function print() {
for (let i = 0; i < 10; i++) {
await sleep(i,Math.random()*1000).then(function(result){
console.log(result)
})
}
}
print()

Explanation

Let’s look at the sleep function first.

const sleep = (i,ms) =>  new Promise(resolve => setTimeout(() => resolve(i), ms));

It takes two parameters: i and ms, the latter of which is the time in milliseconds. It returns a promise that resolves with value i after the specified milliseconds (ms) have passed. This is achieved using the setTimeout ...