JavaScript await in Depth
await pauses the function it sits in, not the page. The value after await is the result of the promise it waits for.
Wait for a promise
The function pauses at await until the timer promise fulfills. The page line logs while the function waits.
function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
(async () => {
console.log("Start");
await wait(50);
console.log("After wait");
})();
console.log("Page keeps going");Read the awaited value
The promise fulfills with the number 7. Await hands that number to the code, which doubles it and logs the result.
function getNumber() {
return new Promise((resolve) => {
setTimeout(() => resolve(7), 50);
});
}
(async () => {
const n = await getNumber();
console.log(n * 2);
})();Await a plain value
Await works on a plain value too. It gives the value back at once, with no promise needed.
(async () => {
const x = await 5;
console.log(x);
})();Await inside a named function
The load function awaits a promise that is already fulfilled. The call line logs first, and the loaded line follows.
async function load() {
const value = await Promise.resolve("Loaded");
console.log(value);
}
load();
console.log("Called");Example
function getWord(word, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(word), ms);
});
}
(async () => {
const first = await getWord("Hello", 50);
const second = await getWord("World", 50);
console.log(first + " " + second);
})();Key points
- await: a keyword that pauses an async function until a promise settles
- The value after await is the fulfilled value of the promise.
- await works only inside an async function.
- While a function waits, the rest of the page keeps running.
- await on a plain value gives that value back at once.
- The lines after await run only when the promise settles.
In this example, the async function awaits the first word, then awaits the second word. Each await pauses the function until its timer finishes. The final line logs both words together.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does await pause?