In JavaScript, asynchronous operations return a Promise, so the function does not immediately receive the final value. To use the resolved value before continuing, you can use async/await or .then().
- Use async/await to wait for a Promise to settle before executing the next statement.
- Use .then() to handle the value when the Promise resolves.
- An async function always returns a Promise.
- await can be used inside an async function to wait for a Promise to resolve.
Using setTimeout() to Wait for a Promise
The setTimeout() method can be used to create a Promise that resolves after a specified delay. This is useful for simulating asynchronous operations, but the delay itself does not guarantee that another asynchronous operation has completed.
Example:
// Returns a Promise that resolves after the specified delay
const wait = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// Handles errors
function failureCallback() {
console.log("This is failure callback");
}
// Wait for 4 seconds
wait(4000)
.then(() => {
console.log("Waited for 4 seconds");
throw new Error("Error occurred");
})
.catch(() => {
failureCallback();
});
// Wait for 2 seconds
wait(2000).then(() => {
console.log("Waited for 2 seconds");
});
Output
Waited for 2 seconds Waited for 4 seconds This is failure callback
- wait() returns a Promise that resolves after the specified number of milliseconds.
- .then() executes when the Promise is resolved.
- .catch() handles the error thrown inside .then().
- The two wait() calls run independently, so the 2-second operation completes before the 4-second operation.
Note: setTimeout() only introduces a delay. When waiting for a real asynchronous operation, use the Promise returned by that operation instead of guessing how long it will take.
Using async/await
The async and await keywords provide a cleaner way to work with Promises.
- async makes a function return a Promise.
- await pauses execution of that async function until the Promise settles.
- The resolved value can be stored in a variable and used like a normal value.
Example:
// Returns a Promise after 2 seconds
function firstFunction() {
console.log("Entered first function");
return new Promise(resolve => {
setTimeout(() => {
console.log("Returned first promise");
resolve("This is first promise");
}, 2000);
});
}
// Returns a Promise after 4 seconds
function secondFunction() {
console.log("Entered second function");
return new Promise(resolve => {
setTimeout(() => {
console.log("Returned second promise");
resolve("This is second promise");
}, 4000);
});
}
async function asyncFunction() {
console.log("Async function called");
const firstPromise = await firstFunction();
console.log(
"After waiting for 2 seconds, the first Promise returned:"
);
console.log(firstPromise);
const secondPromise = await secondFunction();
console.log(
"After waiting for 4 seconds, the second Promise returned:"
);
console.log(secondPromise);
}
asyncFunction();
Output
Async function called Entered first function Returned first promise After waiting for 2 seconds, the first Promise returned: This is first promise Entered second function Returned second promise After...
- asyncFunction() starts executing.
- await firstFunction() waits for the first Promise to resolve.
- The resolved value is stored in firstPromise.
- Only after the first Promise resolves does secondFunction() execute.
- await secondFunction() then waits for the second Promise to resolve.
Using .then() Instead of await
The same operation can be written using .then():
firstFunction()
.then(firstPromise => {
console.log(firstPromise);
return secondFunction();
})
.then(secondPromise => {
console.log(secondPromise);
})
.catch(error => {
console.error(error);
});
For sequential asynchronous operations, async/await is generally easier to read, while .then() is useful when working directly with Promise chains.