async / await
async/await is syntactic sugar over promises that lets you write
asynchronous code that reads as if it were synchronous.
async function loadUser() {
const response = await fetch("/user"); // waits for the promise
const data = await response.json();
return data;
}
- The keyword
asyncin front of a function makes it always return a promise. - The keyword
awaitpauses the function until the promise resolves, and returns its value. It can only be used insideasyncfunctions.
To handle errors with await, you use try...catch:
async function load() {
try {
const data = await requestData();
return data;
} catch (error) {
console.log("Failed:", error.message);
}
}
Promise.all: wait for several at once
When you have several independent tasks, don't await them one by one: launch them
in parallel with Promise.all, which fulfills when all of them finish.
const [a, b] = await Promise.all([requestA(), requestB()]);
Remember that an async function is identified by
fn.constructor.name === "AsyncFunction", and that calling any async
function returns an object that is instanceof Promise.
Examples
An async function always returns a promise
async function greet() {
return "hello";
}
console.log(greet.constructor.name); // "AsyncFunction"
console.log(greet() instanceof Promise); // true
greet().then((v) => console.log(v)); // "hello"