Search⌘ K
AI Features

Await Expressions

Explore how to use await expressions within async functions to handle promises more efficiently in JavaScript. Understand how await pauses execution until a promise resolves or rejects, enabling synchronous-like coding for asynchronous operations. Learn how to catch errors using try-catch blocks and how await seamlessly handles both promises and non-promise values.

Using await expressions

The await expressions are designed to make working with promises simpler. Instead of manually assigning fulfillment and rejection handlers, any promise used in an await expression behaves more like code in a synchronous function. The expression returns the fulfilled value of a promise when it succeeds and throws the rejection value when the promise fails. This allows us to easily assign the result of an await expression to a variable and catch any rejections using a try-catch statement. Here’s an example of using the fetch() API without await:

function retrieveJsonData(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Unexpected status code: ${
response.status
} ${response.statusText}`);
}
})
.catch(reason => console.error(reason.message));
}
Using fetch() without await

The ...