Sikau

JavaScript · Day 53 · about 30 min

async and await

Waiting code that reads top to bottom.

The best of both

Promises fixed callback hell, but .then chains can still feel twisty. async and await let you write waiting code that reads like a normal recipe, top to bottom.

await inside async

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function cookDinner() {
  console.log("Washing rice");
  await wait(300);
  console.log("Rice cooked");
  await wait(300);
  console.log("Dal cooked");
  return "Dinner served 🍛";
}

cookDinner().then((msg) => console.log(msg));

The rest of this lesson

  • Errors with try and catchexplain
  • await, one line at a timeexplain
  • Predict the orderpredict
  • Who logs first?predict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript