Sequential Awaits Chain Dependent Steps

Steps that consume the previous result must await in order, while unrelated calls belong in the same Promise.all so they run alongside the chain.

JavascriptData Fetching

Code

javascriptsnippet
28 lines
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function fetchProfile() {
  await sleep(10);
  return { userId: 7, locale: 'zh-CN' };
}

async function fetchOrders(userId) {
  await sleep(10);
  return [`order-${userId}-1`, `order-${userId}-2`];
}

async function fetchNotice() {
  await sleep(10);
  return 'maintenance at 02:00';
}

// 依赖链:每一步都需要上一步的返回值,只能顺序 await
const profile = await fetchProfile();
const orders = await fetchOrders(profile.userId);
console.log('chain:', profile.locale, orders.join(','));

// 与链无关的调用不要排在链尾:放进同一个 Promise.all 并行
const [chained, notice] = await Promise.all([
  fetchProfile().then((p) => fetchOrders(p.userId)),
  fetchNotice(),
]);
console.log('parallel:', chained.length, notice);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

chain: zh-CN order-7-1,order-7-2
parallel: 2 maintenance at 02:00

The dependent chain

fetchOrders needs profile.userId, so the first block awaits fetchProfile, then fetchOrders(profile.userId) — ordering is forced by data flow, and the chain line prints the joined results.

Parallelizing the unlinked call

fetchNotice depends on nothing, so the second block pairs the whole chain (fetchProfile().then(p => fetchOrders(p.userId))) with fetchNotice inside one Promise.all. Both start immediately; the chain still runs in order internally while notice runs alongside.

The anti-pattern named

Awaiting the notice before or after the chain serially would add its full latency on top; the demo’s parallel block is the structural fix.

FAQ

Why can't the chain steps run in parallel?
Each step consumes the previous step's return value (fetchOrders needs profile.userId), so the awaits are forced to run in sequence.
Where should an unrelated call go?
Into the same Promise.all as the chain, so it runs alongside instead of being serialized before or after the dependent steps.