JavaScript promises, async, and await

A promise represents a value that will be available later. It is pending, then either fulfilled with a value or rejected with an error. An async function always returns a promise, and await pauses that function until a promise settles, without blocking the rest of the program. Code after the call to an async function runs before the awaited work finishes.

JavaScript
function delay(value, ms) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

async function main() {
  console.log("start");
  const a = await delay("A", 20);
  console.log("got " + a);

  const [b, c] = await Promise.all([delay("B", 30), delay("C", 10)]);
  console.log("got " + b + c);

  try {
    await Promise.reject(new Error("boom"));
  } catch (error) {
    console.log("caught " + error.message);
  }

  const winner = await Promise.race([delay("slow", 60), delay("fast", 5)]);
  console.log("race winner " + winner);
}

main().then(() => console.log("done"));
console.log("after main() call");
Read the full lesson