Open In App

How to call promise inside another promise in JavaScript ?

In JavaScript, to call promise inside another promise we first declare a promise using its basic syntax and further execute this promise then create another which is to be called inside the previous promise for its execution.

Promise is basically a JavaScript object which is responsible for handling all the asynchronous operations or activities like fetching data from the API and so on.



Syntax:

let promise = new Promise(function(resolve, reject){
//do something
});

Parameters:

Example: This example shows the declaration and execution of a promise in JavaScript.



Here we need to first declare a Promise by using the Promise syntax, and we will be using the then() method for its execution and then inside that then() method we will create another promise by using the same Promise syntax as illustrated above, and then we will call our result of first inside that new Promise.




let promise = new Promise((resolve, reject)=>{
    resolve('GeeksforGeeks');
})
.then((result)=>{
    console.log(result);
})

Output
GeeksforGeeks

Now after analyzing the above facts related to our problem statement let’s see the following approaches to understand and analyze our problem statement more effectively.

Naive Approach

Example: Below is the example.




let firstPromise = new Promise((resolve, reject) => {
    resolve("Hello, ");
})
    .then((result) => {
        console.log(result);
        return new Promise((resolve, reject) => {
            resolve(result + "GeeksforGeeks!");
        })
            .then((result) => {
                console.log(result);
            });
    });

Output
Hello, 
Hello, GeeksforGeeks!

Using setTimeout() method to call promise inside promise

Example: This example demonstrates the use of setTimeout() method to call a promise inside another promise.




let firstPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Hello ");
    }, 100);
})
    .then((result) => {
        console.log(result);
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(result + "GeeksforGeeks!");
            }, 200);
        })
            .then((result) => {
                console.log(result);
            });
    });

Output
Hello 
Hello GeeksforGeeks!

Article Tags :