How to use async and await in JavaScript
· Category: JavaScript
Short answer
async declares a function that implicitly returns a Promise, and await pauses execution until the Promise settles, making async code linear and readable.
Steps
- Declare an async function:
javascript async function getUser() { const response = await fetch("/api/user"); if (!response.ok) throw new Error("Failed"); return await response.json(); } - Use
try/catchfor error handling:javascript async function load() { try { const user = await getUser(); console.log(user); } catch (err) { console.error(err); } } - Await multiple parallel tasks:
javascript const [a, b] = await Promise.all([taskA(), taskB()]);
Tips
awaitonly works insideasyncfunctions and at the top level of modules in modern environments.- Prefer
awaitover long.then()chains for readability.
Common issues
- Forgetting
awaiton a Promise causes the code to use the Promise object instead of its resolved value. awaitinside a loop runs sequentially; wrap inPromise.allfor parallelism.