In this tutorial, you’ll learn how to handle JavaScript promise inside promise. Sometimes it’s required that the result from a promise is the input to another promise and so on. So, let’s see how a promise inside promise or promise chaining can be implemented.
Using Promise Inside Promise
Let’s start by creating a project directory called promise_inside. Navigate to the project directory and initialize the project using npm.
mkdir promise_inside
cd promise_inside
npm init
Once the project has been initialized, install the node module request. You’ll be using request to make REST API calls.
# install request module using npm
npm install --save request
Create a helper library called helper.js inside the project directory. Add the following code to helper.js :
/* 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)
});
})
}
}
helper.js provides a method called make_API_call to make REST API calls using request module. It returns a promise which gets resolved once the API call returns the response.
Create a file called main.js. Inside main.js you’ll import the helper.js and use make_API_call method to make API calls.
const helper = require('./helper')
function getUserPostDetails() {
return helper.make_API_call('https://jsonplaceholder.typicode.com/users')
.then((users) => {
let promises = []
users.forEach((user) => {
promises.push(helper.make_API_call('https://jsonplaceholder.typicode.com/posts?userId=' + user.id))
})
return Promise.all(promises)
})
}
As seen in the above code, you made an API call using the helper method make_API_call. This call returns a promise when resolved with a list of users. Once this promise has been resolved, users returned from the promise resolution is iterated to get list of posts created by users. This creates an array of promise which is returned. This is how a promise inside promise works.
The function getUserPostDetails returns an array of promises which when resolved will return the posts related to users.
Here is the main.js file :
/* main.js */
const helper = require('./helper')
function getUserPostDetails() {
return helper.make_API_call('https://jsonplaceholder.typicode.com/users')
.then((users) => {
let promises = []
users.forEach((user) => {
promises.push(helper.make_API_call('https://jsonplaceholder.typicode.com/posts?userId=' + user.id))
})
return Promise.all(promises)
})
}
getUserPostDetails()
.then((result) => {
console.log('result is ',result)
})
Final Thoughts
In this tutorial, you learned about promise chaining or using promise inside promise. How was learning experience ? Do let us know your thoughts in the comments below.
Source code from this tutorial is available on GitHub.