JavaScript Async & Await
`async`/`await` is modern syntax built on top of Promises that lets asynchronous code read almost like synchronous code, improving readability significantly.
An `async` function always returns a Promise, and inside it, `await` pauses execution until the awaited Promise settles, without blocking the rest of the browser.
async functions
Adding `async` before a function definition means it always returns a Promise, and lets you use `await` inside it.
await and error handling
`await promise` pauses the async function until the promise resolves, returning its value. Wrap awaited code in try/catch to handle rejections.
async function getValue() {
return 42;
}
getValue().then(v => console.log(v));42An async function automatically wraps its return value in a resolved Promise.
async function run() {
let result = await Promise.resolve("done");
console.log(result);
}
run();doneawait pauses until the Promise resolves, then returns its value directly.
Key points
- async functions always return a Promise.
- await pauses execution until a Promise settles.
- try/catch around await handles rejected Promises.
- async/await makes asynchronous code look synchronous and readable.
