WeCodeAcademy

Node.js Promises and async/await

ExampleNode.js
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error("boom")), ms));

async function main() {
  console.log(await wait(20, "first"));

  const [a, b] = await Promise.all([wait(30, "A"), wait(10, "B")]);
  console.log(a, b);

  console.log(await Promise.race([wait(50, "slow"), wait(10, "fast")]));

  try {
    await fail(10);
  } catch (err) {
    console.log("caught:", err.message);
  }

  const results = await Promise.allSettled([wait(5, "ok"), fail(5)]);
  console.log(results.map((r) => r.status));
}

main().then(() => console.log("done"));
Output
first
A B
fast
caught: boom
[ 'fulfilled', 'rejected' ]
done
Quick check

What does Promise.all do?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.