Sikau

Advanced JavaScript · Day 20 · about 30 min

Async patterns

Timeouts, retries and sequential vs parallel.

When the network misbehaves

Real networks are slow, flaky and sometimes silent. Professional code gives up after a while (timeout), tries again (retry), and knows when to run things one after another versus all at once.

Timeout with race, and retry with a loop

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function withTimeout(promise, ms) {
  const timer = sleep(ms).then(() => {
    throw new Error("Timed out");
  });
  return Promise.race([promise, timer]);
}

async function retry(task, attempts) {
  for (let i = 1; i <= attempts; i++) {
    try {
      return await task();
    } catch (err) {
      console.log("Attempt", i, "failed:", err.message);
      if (i === attempts) throw err;
      await sleep(50 * i);
    }
  }
}

let calls = 0;
const flaky = async () => {
  calls++;
  if (calls < 3) throw new Error("network");
  return "loaded";
};
retry(flaky, 5).then((r) => console.log(r));
withTimeout(sleep(500), 100).catch((e) => console.log(e.message));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const steps = [100, 100, 100];

async function sequential() {
  const t = Date.now();
  for (const ms of steps) await sleep(ms);
  console.log("sequential", Date.now() - t, "ms");
}
async function parallel() {
  const t = Date.now();
  await Promise.all(steps.map((ms) => sleep(ms)));
  console.log("parallel", Date.now() - t, "ms");
}
sequential().then(parallel);

The rest of this lesson

  • Retrying politelyexplain
  • Timeouts that clean upexplain
  • Predictpredict
  • Backoff delayspredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript