Await
While the .then() and .catch() callbacks work perfectly well for handling Promises, modern JavaScript introduced a much cleaner syntax: the await keyword.
The await keyword is placed directly in front of a Promise. It effectively “pauses” the execution of that specific function until the Promise resolves, and then it immediately returns the resolved value directly into a variable.
.then vs await
Here is how you handle a Promise using the older .then() syntax:
myPromise.then((message) => {
console.log(`Resolved with ${message}`);
});
And here is the exact same logic using await:
// The code pauses here until myPromise resolves
const message = await myPromise;
console.log(`Resolved with ${message}`);
Handling Rejections with Await
When using await, if the Promise is rejected (fails), it will throw a standard JavaScript error. This means you can use standard try/catch blocks to handle failures cleanly, keeping your asynchronous error handling consistent with your synchronous error handling.
try {
const message = await myPromise;
console.log(`Resolved with ${message}`);
} catch (error) {
// If myPromise rejects, execution jumps here
console.log(`Rejected with ${error}`);
}
Note: You are highly encouraged to use await over .then() whenever possible, as it makes asynchronous code look and read almost exactly like synchronous code.