async and await
An async function is a function that can pause and wait. Await pauses the function until a promise finishes.
An async function returns a promise
This async function returns Hello. The then call reads the promise value.
async function greet() {
return "Hello";
}
greet().then((value) => {
console.log(value);
});A function that waits
This function returns a promise that resolves with Ready.
function wait() {
return new Promise((resolve) => {
setTimeout(() => resolve("Ready"), 100);
});
}Waiting with await
This waits for the wait function from the last snippet.
async function main() {
const result = await wait();
console.log(result);
}
main();Example
function wait() {
return new Promise((resolve) => {
setTimeout(() => resolve("Ready"), 100);
});
}
async function main() {
console.log("Waiting");
const result = await wait();
console.log(result);
}
main();
console.log("Started");Key points
- Write async before function to make an async function.
- An async function always returns a promise.
- Await pauses only its own function.
- Await takes the value from a fulfilled promise.
- Use await only inside an async function.
- The rest of the program keeps running during a wait.
In this example, wait returns a promise that resolves with Ready. The main function prints Waiting and then awaits that promise. The program prints Started while main waits. Ready prints last, when the promise fulfills.
Note
An async function runs its first lines at once, until the first await.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does await do?