Tsallaka zuwa abun ciki
Justice Tech School

Callbacks, Promises and async/await

Slow work such as files and networks runs without blocking. Old APIs use callbacks, newer ones return promises. async and await make promise code read top to bottom. Promise.all runs tasks in parallel.

Example
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
(async () => {
  console.log("start");
  const a = await wait(20, "A");
  console.log(a);
  const all = await Promise.all([wait(30, 1), wait(10, 2)]);
  console.log(all);
  try {
    await Promise.reject(new Error("boom"));
  } catch (e) {
    console.log("caught", e.message);
  }
})();

Result

start
A
[ 1, 2 ]
caught boom

Exercise

Wait for a promise.

const v =  wait(10);

Quiz Test

Which runs promises in parallel?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.