In JavaScript, to wait for a promise to resolve before returning a value, you use async/await or the .then() method-both ensure the code waits for the asynchronous operation to complete before proceeding.
- Use async/await to pause the function execution until the promise resolves.
- Use .then() to handle the resolved value once the promise is completed.
To do that there are two popular ways described below.
Use of setTimeout() function
Using the setTimeout() function to wait for a promise involves delaying the execution of code by a specified time, allowing the promise to resolve before continuing. This method is less precise as it relies on estimated timing rather than directly handling the promise's resolution.
// Returns a promise that resolves after `ms` milliseconds
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
// Logs failure message
function failureCallback() {
console.log("This is failure callback");
}
// Waits 4 seconds, then logs and throws an error
wait(4 * 1000).then(() => {
console.log("waited for 4 seconds");
throw new Error("error occurred");
}).catch(() => {
failureCallback(); // Handles the error
});
// Waits 2 seconds, then logs message
wait(2 * 1000).then(() =>
console.log("waited for 2 seconds"));
Use of async or await() function
Using async and await in JavaScript allows you to handle asynchronous operations more easily. The async keyword makes a function return a promise, while await pauses the function execution until the promise resolves, ensuring sequential and reliable code execution.
// 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