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

  1. 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(); }
  2. Use try/catch for error handling: javascript async function load() { try { const user = await getUser(); console.log(user); } catch (err) { console.error(err); } }
  3. Await multiple parallel tasks: javascript const [a, b] = await Promise.all([taskA(), taskB()]);

Tips

  • await only works inside async functions and at the top level of modules in modern environments.
  • Prefer await over long .then() chains for readability.

Common issues

  • Forgetting await on a Promise causes the code to use the Promise object instead of its resolved value.
  • await inside a loop runs sequentially; wrap in Promise.all for parallelism.