Promises and async / await

Wait for asynchronous work with async / await, run tasks together with Promise.all, and handle errors.

Runs in Zerethon IDE · Node.js 22 Official JavaScript documentation ↗
main.js
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function job(name, ms) {
  await sleep(ms);
  return `${name} done`;
}

async function main() {
  console.log(await job('first', 20));
  const results = await Promise.all([job('a', 30), job('b', 10)]);
  console.log(results);
  try {
    await Promise.reject(new Error('boom'));
  } catch (err) {
    console.log('caught:', err.message);
  }
}

main();

Output

first done
[ 'a done', 'b done' ]
caught: boom
  • await only works inside an async function (or at the top level of an ES module).
  • Promise.all keeps the order of its inputs, even when later tasks finish first.
  • A run ends when nothing is left to wait for — and is stopped at the time limit (10 s) if a timer or promise never finishes.

Related topics

Official references