Learn async while loop in Nodejs from SCRATCH

This tutorial explains async while loop Nodejs without assuming you understand the concepts of promises, looping, and timers.

It is divided into four sections: how JavaScript reads your code, the concept of promises, loops, and the need for asynchronous code in while loops and implementing async while loop Nodejs step-by-step.

Advertisement

Let's get started.

 

Section-1: How does the JavaScript engine read your code?

JavaScript engines read your code from top to bottom. If a code portion takes longer to execute, the subsequent code portions will wait longer to run. That behavior is called synchronous.

However, with the help of callback functions, timer APIs, and promises, you can make JavaScript code run asynchronously. Here is an example.

Assume you have two calculations.

console.log(2 + 3)
console.log(3 + 5)

When you run the code, the terminal prints 5 followed by 8. What if you want to see 8 before 5? You can control the output with the setTimeout API.

const firstCalCulation = () => console.log(2 + 3)
const secondCalCulation = () => console.log(3 + 5)

setTimeout(firstCalCulation, 2000)
setTimeout(secondCalCulation, 1000)

The setTimeout API receives a function as an input and runs it after the specified number of milliseconds. In the above example, we run the firstCalCulation and secondCalCulation functions which print the output of 2 + 3 and 3 + 5 after 2000 milliseconds and 1000 milliseconds, respectively.

Advertisement

Since JavaScript does not wait for the pending computation in the firstCalCulation function, it will run the second function when the first one has not completed running.

 

Control the program flow with callback functions

As it stands, the two functions run independently of each other. Nevertheless, we can make the first calculation depend on the second calculation such that you won't see the first result when the second function has not finished executing.

const firstFunction = (firstCalculation, callback) => {
     console.log(firstCalculation)
     callback()
}

const secondCalCulation = () => console.log(3 + 5)
const secondFunction = () => setTimeout(secondCalCulation, 1000)

firstFunction(2 + 3, secondFunction)

A delay in execution of the secondFunction will prevent the firstFunction from executing because the first function cannot run without its parameters: firstCalculation and the callback function.

A function received as a parameter to another function is called a callback function. It simply implies, "Do something and call me back when you are done."

The above code would be unmaintainable if we were to do lengthy computations that lead to the nesting of multiple callbacks. That calls for understanding the role of promises in async while loop Nodejs computations.

 

Section-2: Understand promises before applying async while loop Nodejs

The most familiar way to make the synchronous JavaScript code run asynchronously is to use the Promise API.

Advertisement

The most straightforward interpretation of a promise in JavaScript is, "I promise to execute the given code. If the promise is resolved, use the returned data for subsequent sections of your computations. If I fail to resolve my promise, I will reject the order with an error message."

The Promise object takes a callback function with two (method) arguments: resolve() and reject(). The resolve() function runs when the expected process completes successfully, while the reject() function catches errors that may occur during the code execution.

const computation = () => {

     return new Promise( (resolve, reject) => {

        let doSomething = true
        doSomething ? resolve('Done!') : reject('Failed to execute your request')

     })

}

You can then handle the output using then-catch

computation()
.then( result => console.log(result)) // Print the output on success.
.catch( error => console.log(error)) // otherwise, print the error message.

or async-wait.

const showOutput = async () => {
     const data = await computation()
     console.log(data)
}
showOutput()

Learn async while loop in Nodejs from SCRATCH

The async-await syntax is an alternative to joining multiple .then()s or Promise.all() and one catch() function.

async-await always runs in a function. Such function is said to be asynchronous, although you (as the programmer) write the code as if you are writing synchronous code.

Advertisement

You will not always need to create the Promise function because most Nodejs modules and APIs are built to run asynchronously.

Let's understand the concept of looping before practically implementing async while loop Nodejs.

 

Section-3: The role of asynchronous code in while loops

You probably wonder the reason for running code in async while loop Nodejs. There could be many reasons to attempt looping asynchronous code.

One of the key reasons is to fetch multiple resources in a controlled environment. It would be best if you familiarized yourself with loops before doing that.

A loop is a portion of code that repeats a particular code as long as a condition is true.

The three main loops in JavaScript are for, while, and do-while loops. for loops are mainly used when the number of repetitions is known.

Advertisement
for (let i = 1; i < 11; i++) {
     //do something 10 times
}

On the other hand, while loops are mainly used when the number of repetitions is unknown at the start. For example, you could be unsure about the number of posts to have been posted when a user visits your application.

// Initially there are no posts to read.
let posts = []

// A method to create posts
const createPost = (post) => {
     posts.push(post)
}

// A method to read posts.
const readPost = () => {
     let counter = 0
     while (counter < posts.length) {
         console.log(posts[counter])
         counter++
     }
}

// create three posts
createPost('Post one')
createPost('Post two')
createPost('Post three')

// Now, we have posts to loop through and read.
readPost()

Learn async while loop in Nodejs from SCRATCH

The while loop is divided into the initializer, condition, and increment.

  • The initializer marks the starting point of the loop. For example, start counting at the first post.
  • The condition determines when to stop looping. For example, repeat the code block as long as the number of posts is less than the counter value.
  • The increment/decrement takes us to the next round of looping. For example, we increase and reassign the counter's value till it equates to the number of the posts.

Now that you understand asynchronous programming and while loops, let's see how to combine the two concepts.

 

Lab setup to practice Async while loop in Nodejs

Install the latest version of Nodejs, then head over to your terminal and create two files.

touch file1.js file2.js

Open the files using a code editor like Visual Studio Code.

Learn async while loop in Nodejs from SCRATCH

Now let's implement async while loop Nodejs with the following examples.

Advertisement

 

Section-4: Async while loop Nodejs examples

Example-1: Delay loops

Assume you want to print 10 post IDs after the specified milliseconds. Since the execution of a setTimeout API run directly inside a loop gets deferred, we can use recursion or async while loop Nodejs as follows.

Open file1.js and add the following code.

const delayExecution = (ms) => {

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve()
        }, ms)
    })
}

const showIDs = async () => {

    let counter = 1

    while (counter <= 5) {
        await delayExecution(1000)
        console.log(`post id ${counter}`)
        counter++
    }

}

showIDs()

The delayExecution() function returns a promise which resolves a setTimeout after the ms seconds that the function receives whenever we loop through the 1 to 5 in the asynchronous showIDs() function.

async while loop Nodejs

Let's look at another example, where async while loop Nodejs handles external API data.

 

Example-2: Async while loop Nodejs with external API data

Assume you want to fetch only the first 10 post titles from the JSONPlaceholder API posts. Open file2.js and write the following code.

const firstTen = async () => {
    let counter = 0
    while (counter < 10) {
        const res = await fetch('https://jsonplaceholder.typicode.com/posts')
        const posts = await res.json()
        console.log(`${counter + 1}: ${posts[counter].title}`)
        counter++
    }
}

firstTen()

We get the data using the asynchronous firstTen() function by applying the Nodejs fetch API (available in Node.js version 17.5+).

Advertisement

We then convert the (JSON) data into (an array) objects for easier looping. Next, we print each numbered post title. Lastly, we call the firstTen() function and view the result on the console output.

Learn async while loop in Nodejs from SCRATCH

 

Conclusion

The knowledge on async while loop Nodejs helps you control when and how you receive data. As shown in this tutorial, it would be best to deeply understand asynchronous programming, loops, and the need for running asynchronous code inside while loops before using async-await with while loops.

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X