Open In App
Related Articles

How to wait for a promise to finish before returning the variable of a function ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Here a promise is a returned object from an asynchronous function, and callback methods can be added based on the previous function’s result. It is done for back-to-back execution of functions acting like a queue or chain of functions. So as the functions are in the queue, the functions following it must wait for the previous function’s result.

To do that there is two popular way described below.

Use of setTimeout() function

In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds.

Example: This example describes the setTimeout() method to wait for a promise to finish before returning the variable of a function.

javascript

const wait = ms => new Promise(resolve =>
    setTimeout(resolve, ms));
 
function failureCallback() {
    console.log("This is failure callback");
}
 
wait(4 * 1000).then(() => {
    console.log("waited for 4 seconds");
    throw new Error("error occurred");
}).catch(() => {
    failureCallback();
});
 
wait(2 * 1000).then(() =>
    console.log("waited for 2 seconds"));

                    

Output:

Output

Use of async or await() function

This method can be used if the exact time required in setTimeout() cannot be specified. The async keyword is used to create an asynchronous function that returns a promise that is either rejected or resolved. The promise is rejected when there is an uncaught exception thrown from that function or it is resolved otherwise. The await keyword is used inside an async function to pause its execution and wait for the promise. The below program will illustrate the approach: 

Example: This example describes the async/await approach to wait for a promise to finish before returning the variable of a function.

javascript

// This function returns promise after 2 seconds
let first_function = function () {
    console.log("Entered first function");
    return new Promise(resolve => {
        setTimeout(function () {
            resolve("\t\t This is first promise");
            console.log("Returned first promise");
        }, 2000);
    });
};
 
// This function executes returns promise after 4 seconds
let second_function = function () {
    console.log("Entered second function");
    return new Promise(resolve => {
        setTimeout(function () {
            resolve("\t\t This is second promise");
            console.log("Returned second promise");
        }, 4000);
    });
};
 
let async_function = async function () {
    console.log('async function called');
 
    const first_promise = await first_function();
    console.log("After awaiting for 2 seconds," +
        "the promise returned from first function is:");
    console.log(first_promise);
 
    const second_promise = await second_function();
    console.log("After awaiting for 4 seconds, the" +
        "promise returned from second function is:");
    console.log(second_promise);
}
 
async_function();

                    

Output:

async function called
Entered first function
Returned first promise
After awaiting for 2 seconds, the promise returned from first function is:
This is first promise
Entered second function
Returned second promise
After awaiting for 4 seconds, the promise returned from second function is:
This is second promise


Last Updated : 07 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads