Async/Await Architecture

Published by Brayan K

async/await is JavaScript syntax that lets you write asynchronous, Promise-based code in a clean, sequential style, pausing on await until a Promise settles instead of chaining callbacks.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Decide who starts work and who owns its result

The hard part of an async workflow is often its contract: which operations may start together, how many may remain in flight, what happens to a failed item, and when the caller can trust the final result. Async/Await owns the syntax and basic sequential-versus-independent examples. Here we build a bounded queue with an explicit outcome for every item.

let release;
const gate = new Promise(resolve => { release = resolve; });
let active = 0;
let peak = 0;
async function work(id) {
  active++; // Count operations that have started but have not completed.
  peak = Math.max(peak, active);
  await gate; // Hold every operation at the same controlled boundary.
  active--;
  return id.toUpperCase();
}
const pending = ["a", "b", "c", "d"].map(work); // Starts all four now.
console.log("active before all", active, "peak", peak);
const complete = Promise.all(pending); // This does not impose a limit.
release();
console.log((await complete).join(","), "active", active);

// ✅ Expected output:
// active before all 4 peak 4
// A,B,C,D active 0

The limit must control calls to work, before those calls create pending operations. Passing an already-started array to a function named limit cannot undo its starts. This is about overlapping waits, not executing CPU-bound JavaScript simultaneously on this one agent.

Keep queued work lazy

const started = [];
const tasks = ["a", "b", "c"].map(id => () => {
  started.push(id);
  return Promise.resolve(id.toUpperCase());
});
console.log("before calls", started.length);
console.log(await tasks[1]());
console.log(started.join(","));
console.log(await tasks[0]());
console.log(started.join(","));

// ✅ Expected output:
// before calls 0
// B
// b
// A
// b,a

A queue can store input values plus a worker function, or store functions like these. Both let the scheduler choose when to call the operation. They do not replay a promise that already exists. Reusing the same promise only observes the same outcome again.

let calls = 0;
function load() { calls++; return Promise.resolve(calls); }
const existing = load();
console.log(await existing, await existing, calls);
console.log(await load(), calls);

// ✅ Expected output:
// 1 1 1
// 2 2

Retry means calling a producer again under a deliberate policy. Some operations have side effects, so a retry may repeat a write. Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns request retry and timeout decisions.

Choose a result policy before writing the queue

const reasons = [new Error("missing"), undefined];
const results = await Promise.allSettled([
  Promise.resolve("ready"),
  Promise.reject(reasons[0]),
  Promise.reject(reasons[1])
]);
for (const result of results) {
  console.log(result.status, result.status === "fulfilled" ? result.value : String(result.reason));
}
console.log(results[1].reason === reasons[0]);

// ✅ Expected output:
// fulfilled ready
// rejected Error: missing
// rejected undefined
// true

A rejection reason can even be undefined, so truthiness is not a reliable success flag. The queue in this lesson uses status-tagged records, preserves each rejection reason, waits for every item, and keeps results in input order. A different application may stop launching new work after a failure; that is a different policy and needs different tests.

let release;
const pending = new Promise(resolve => { release = resolve; });
let finished = false;
const remaining = pending.then(() => { finished = true; return "done"; });
try {
  await Promise.all([Promise.reject(new Error("first failed")), remaining]);
} catch (error) {
  console.log(error.message, finished);
}
release();
console.log(await remaining, finished);

// ✅ Expected output:
// first failed false
// done true

The remaining operation is still waiting after Promise.all rejects. Promise Combinators (all, race, allSettled, any) owns combinator selection. Neither an early rejection nor Promise.race cancels its losing operations.

Claim an index before awaiting its work

const items = ["a", "b", "c"];
let next = 0;
const claims = [];
async function runner(name) {
  while (next < items.length) {
    const index = next++;
    claims.push(name + ":" + index);
    await Promise.resolve(items[index]);
  }
}
await Promise.all([runner("left"), runner("right")]);
console.log(claims.join(","));
console.log(next);

// ✅ Expected output:
// left:0,right:1,left:2
// 3

The index claim is synchronous and contains no await between reading next and incrementing it. On this single JavaScript agent, each runner takes a distinct index before yielding. This is not a cross-thread synchronization technique. Capture the index in a local constant so a completion writes to its own slot.

let finishFirst;
const first = new Promise(resolve => { finishFirst = resolve; });
const completed = [];
const input = [
  first.then(value => { completed.push("first"); return value; }),
  Promise.resolve("B").then(value => { completed.push("second"); return value; })
];
await input[1];
finishFirst("A");
const results = await Promise.all(input);
console.log("completed", completed.join(","));
console.log("results", results.join(","));

// ✅ Expected output:
// completed second,first
// results A,B

Pushing results as operations finish gives completion order. Assigning results[index] preserves input order. Neither is universally correct: choose the contract the caller needs, name it clearly, and verify out-of-order completion rather than testing only immediately resolved work.

Contain a worker failure at the item boundary

async function observe(work, value) {
  try { return { status: "fulfilled", value: await work(value) }; }
  catch (reason) { return { status: "rejected", reason }; }
}
const syncReason = new Error("sync");
const asyncReason = new Error("async");
const a = await observe(() => { throw syncReason; }, 1);
const b = await observe(() => Promise.reject(asyncReason), 2);
const c = await observe(value => value * 3, 3);
console.log(a.status, a.reason === syncReason);
console.log(b.status, b.reason === asyncReason);
console.log(c.status, c.value);

// ✅ Expected output:
// rejected true
// rejected true
// fulfilled 9

Calling work inside try catches a synchronous throw; awaiting its returned value also catches a rejected promise. The runner can then continue with another item. If you omit this boundary, one runner may exit early and leave queued items unvisited. Error Handling owns throwing, narrow catches and error identity.

function validateLimit(limit) {
  if (!Number.isInteger(limit) || limit < 1 || limit > 32) {
    throw new RangeError("limit must be an integer from 1 to 32");
  }
}
validateLimit(0);

// ✅ Expected error:
// RangeError: limit must be an integer from 1 to 32

Zero runners could otherwise return an array of empty slots while doing no work. The upper bound of 32 is this exercise’s explicit API choice, not a browser rule or a recommendation for every service. Concurrency controls how many calls remain pending; it does not enforce a requests-per-second rate.

Snapshot the queue, and state what the snapshot does not protect

const source = [{ name: "A" }, { name: "B" }];
const snapshot = source.slice();
source.reverse();
source.push({ name: "C" });
console.log(snapshot.map(item => item.name).join(","));
source[1].name = "changed";
console.log(snapshot[0].name);
console.log(source.length, snapshot.length);

// ✅ Expected output:
// A,B
// changed
// 3 2

A shallow copy prevents later appends or reordering of the caller’s array from changing which slots the queue visits. Its element objects are still shared. The worker owns any mutation it performs. The brief accepts a plain array, visits every index (including a missing slot as undefined), and does not clone arbitrary object graphs.

const items = ["a", , "c"];
const visited = [];
for (let index = 0; index < items.length; index++) visited.push(index + ":" + String(items[index]));
console.log(visited.join(","));
console.log(Object.hasOwn(items, 1));

// ✅ Expected output:
// 0:a,1:undefined,2:c
// false

This differs from Array.prototype.map, which skips holes. Spelling out the contract keeps that edge case from silently changing when the implementation changes.

Cancellation requires cooperation from the operation

const controller = new AbortController();
let release;
const pending = new Promise(resolve => { release = resolve; });
controller.abort("no longer needed");
console.log(controller.signal.aborted, controller.signal.reason);
release("still completed");
console.log(await pending);

// ✅ Expected output:
// true no longer needed
// still completed

The pending operation never inspected or subscribed to this signal. A queue that supports cancellation must define both what happens to unstarted items and how active operations receive a signal. AbortController & Cancelling Async Work owns implementing that cooperation. This lesson’s queue has no cancellation or deadline: a never-settled worker keeps it pending.

Guided exercise: record failure without losing the item’s slot

Fill the literal hints. Record a status for both outcomes, preserve the rejection reason, and keep results in input order. This small sequential exercise isolates the result policy before the independent concurrency brief.

const results = [];
for (const value of [2, -1, 4]) {
  try {
    if (value < 0) throw new Error("negative");
    results.push({ status: "___", value: value * 2 }); // 👉 replace ___ with fulfilled
  } catch (reason) {
    results.push({ status: "___", reason }); // 👉 replace ___ with rejected
  }
}
console.log(results.map(result => result.___).join(",")); // 👉 replace ___ with status
console.log(results[1].reason.message);

// ✅ Expected output:
// fulfilled,rejected,fulfilled
// negative

Independent brief: process every item with bounded concurrency

Implement async mapSettledLimit(items, limit, work). Validate items as an array, limit as an integer from 1 to 32, and work as a function before starting any item. Copy the array once. Visit every index exactly once with work(value, index), including holes as undefined. At most limit calls may be in flight. Return status-tagged outcomes in input order, preserve the exact failure reason, and continue after an item fails. An empty array returns an empty array without calling work.

Check controlled out-of-order completion with a peak active count of two, a synchronous throw, a rejected promise whose reason is undefined, an empty list, holes, a limit larger than the list, invalid inputs, and a caller that changes the original array after the queue starts. Do not use clocks to prove the concurrency limit.

async function mapSettledLimit(items, limit, work) {
  if (!Array.isArray(items)) throw new TypeError("items must be an array");
  if (!Number.isInteger(limit) || limit < 1 || limit > 32) {
    throw new RangeError("limit must be an integer from 1 to 32");
  }
  if (typeof work !== "function") throw new TypeError("work must be a function");
  const snapshot = items.slice();
  const results = new Array(snapshot.length);
  let next = 0;
  async function runner() {
    while (next < snapshot.length) {
      const index = next++;
      try { results[index] = { status: "fulfilled", value: await work(snapshot[index], index) }; }
      catch (reason) { results[index] = { status: "rejected", reason }; }
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, snapshot.length) }, () => runner()));
  return results;
}
function deferred() {
  let resolve;
  const promise = new Promise(done => { resolve = done; });
  return { promise, resolve };
}
const gates = [deferred(), deferred(), deferred()];
const starts = [deferred(), deferred(), deferred()];
const input = ["A", "B", "C"];
let active = 0, peak = 0;
const completed = [];
const pending = mapSettledLimit(input, 2, async (value, index) => {
  active++;
  peak = Math.max(peak, active);
  starts[index].resolve();
  await gates[index].promise;
  active--;
  completed.push(index);
  return value.toLowerCase();
});
console.log("initial active", active);
input.reverse();
input.push("D");
gates[1].resolve();
await starts[2].promise;
console.log("third started", active);
gates[2].resolve();
gates[0].resolve();
const results = await pending;
console.log("completion", completed.join(","));
console.log("results", results.map(result => result.value).join(","), "peak", peak, "active", active);
const reason = new Error("sync failure");
const mixed = await mapSettledLimit([0, 1, 2], 2, value => {
  if (value === 0) throw reason;
  if (value === 1) return Promise.reject(undefined);
  return 8;
});
console.log(mixed.map(result => result.status).join(","));
console.log(mixed[0].reason === reason, mixed[1].reason === undefined, mixed[2].value);
let emptyCalls = 0;
console.log((await mapSettledLimit([], 2, () => { emptyCalls++; })).length, emptyCalls);
const holes = await mapSettledLimit(["x", , "z"], 32, (value, index) => index + ":" + String(value));
console.log(holes.map(result => result.value).join(","));
let invalidCalls = 0;
for (const [items, limit, work] of [
  [null, 1, () => invalidCalls++],
  [[1], 0, () => invalidCalls++],
  [[1], 1.5, () => invalidCalls++],
  [[1], 33, () => invalidCalls++],
  [[], 1, null]
]) {
  try { await mapSettledLimit(items, limit, work); }
  catch (error) { console.log(error.name, error.message); }
}
console.log("invalid starts", invalidCalls);

// ✅ Expected output:
// initial active 2
// third started 2
// completion 1,2,0
// results a,b,c peak 2 active 0
// rejected,rejected,fulfilled
// true true 8
// 0 0
// 0:x,1:undefined,2:z
// TypeError items must be an array
// RangeError limit must be an integer from 1 to 32
// RangeError limit must be an integer from 1 to 32
// RangeError limit must be an integer from 1 to 32
// TypeError work must be a function
// invalid starts 0

Reference notes

The Promise.all reference documents input-order results and the lack of cancellation on rejection. The AbortSignal reference explains the signal used by cooperating APIs. The bounded queue here is an application contract tested with controlled completion gates, not a built-in scheduler or a universal throughput recommendation.

Practice quiz

What does this complete program print? let calls = 0; const p = Promise.resolve(++calls); console.log(await p, await p, calls);

  • 1 1 1
  • 1 2 2
  • 2 2 2
  • 1 1 2

Answer: 1 1 1. Observing an existing promise again does not repeat its producer.

What does this complete program print? let starts = 0; const work = [1,2,3].map(value => { starts++; return Promise.resolve(value); }); console.log(starts); await Promise.all(work);

  • 0
  • 3
  • 1
  • 2

Answer: 3. map has already invoked the producer for every item before Promise.all sees the promises.

What does this complete program print? const output = await Promise.allSettled([Promise.reject(undefined)]); console.log(output[0].status, output[0].reason);

  • fulfilled undefined
  • rejected null
  • rejected undefined
  • fulfilled null

Answer: rejected undefined. The explicit status distinguishes rejection even when its reason is undefined.

What does this complete program print? const source = ["A","B"]; const copy = source.slice(); source.reverse(); console.log(copy.join(","));

  • B,A
  • A,B,C
  • undefined
  • A,B

Answer: A,B. The copied array retains its order when the original is reversed.

What does this complete program print? const source = [{value:1}]; const copy = source.slice(); source[0].value = 2; console.log(copy[0].value);

  • 2
  • 1
  • undefined
  • TypeError

Answer: 2. A shallow array copy still shares its element objects.

What does this complete program print? let next = 0; const claimed = []; async function runner(){ const index = next++; await Promise.resolve(); claimed.push(index); } await Promise.all([runner(),runner()]); console.log(claimed.join(","));

  • 0,0
  • 0,1
  • 1,2
  • 1,1

Answer: 0,1. Each runner claims an index synchronously before its first await.

What does this complete program print? const c = new AbortController(); const pending = Promise.resolve("done"); c.abort(); console.log(await pending);

  • AbortError
  • undefined
  • done
  • pending

Answer: done. An unrelated promise does not become canceled merely because a signal was aborted.

What does this complete program print? const values = ["A", , "C"]; let count = 0; for(let index=0;index<values.length;index++) count++; console.log(count, Object.hasOwn(values,1));

  • 2 false
  • 3 true
  • 2 true
  • 3 false

Answer: 3 false. An index loop visits the missing slot although the array has no own property at index 1.

Continue this course

Related lessons