async/await

async and await

Example

async functions always return a promise. Inside them, await pauses until a promise settles, so asynchronous code reads like synchronous code:

const delay = (ms, v) => new Promise((res) => setTimeout(() => res(v), ms));

async function checkout() {
  console.log("validating cart...");
  const cart = await delay(20, { total: 499 });
  console.log("charging ₹" + cart.total);
  const receipt = await delay(20, "RCPT-1001");
  return receipt;
}
checkout().then((r) => console.log("done:", r));

Output

validating cart...
charging ₹499
done: RCPT-1001

Error Handling with try...catch

Example

const failAfter = (ms) => new Promise((_, rej) => setTimeout(() => rej(new Error("Network error")), ms));

async function load() {
  try {
    await failAfter(20);
    console.log("not reached");
  } catch (err) {
    console.log("Handled:", err.message);
  } finally {
    console.log("hide spinner");
  }
}
load();

Output

Handled: Network error
hide spinner

Sequential vs Parallel

Example

Awaiting one by one adds up the waiting time. Start independent tasks together with Promise.all:

const delay = (ms, v) => new Promise((res) => setTimeout(() => res(v), ms));

async function main() {
  let t = Date.now();
  await delay(100); await delay(100);
  console.log("sequential ~", Math.round((Date.now() - t) / 100) * 100, "ms");

  t = Date.now();
  await Promise.all([delay(100), delay(100)]);
  console.log("parallel ~", Math.round((Date.now() - t) / 100) * 100, "ms");
}
main();

Output

sequential ~ 200 ms
parallel ~ 100 ms