Promise Inside Loop

How To Handle Promise Inside Loop

In this tutorial, you’ll learn how to handle JavaScript promise inside loop.

Promises are an important concept in JavaScript programming. Getting a basic understanding about how Promises work in JavaScript is a must for every JavaScript developer.

Assuming you have an understanding about how promises work, you will be able to understand this tutorial.

Promise Inside For/ForEach Loop

Create a folder called promise_loop. Initialize the project folder using npm.

mkdir promise_loop
cd promise_loop
npm init

Create a file called helper.js which will make use of the request module to make the API calls. Install the request module using npm.

# install request module
npm install --save request

Add the following code to helper.js :

/* REST API Helper Library - helper.js */
const request = require('request')

module.exports = {
    make_API_call : function(url){
        return new Promise((resolve, reject) => {
            request(url, { json: true }, (err, res, body) => {
              if (err) reject(err)
              resolve(body)
            });
        })
    }
}

Assuming that you have an array of Ids. For each Id inside the array you need to make a REST API call and return the result when the result is available from each API call.

Create a file called main.js and add the following code :

/* main.js file */
const helper = require('./helper')
const user_ids = [1,2,3,4,5]

let promises = [];
user_ids.forEach((id) => {
    promises.push(helper.make_API_call('https://jsonplaceholder.typicode.com/todos/' + id))
})

Promise.all(promises)
.then((result) => {
    console.log('all resolved ', result)
})

As seen in the above code you iterated through the array using forEach loop. For each id an API call is made using the helper.make_API_call method and the resulting promise is stored in an array promises.

The Promise.all method returns a promise when all the promises inside the promises array is resolved. So, this is how you can use promise inside a for each loop. A similar approach can be applied to use promise inside for loop or while in JavaScript or Node.js.

Wrapping It Up

In this tutorial, you learned how to handle promise inside for/ forEach loop. How was your experience trying to understand how to use promise inside loop ? Do let us know your thoughts or suggestions in the comments below.

Source code from this tutorial is available on GitHub.