nachocab
nachocab

Reputation: 14364

How to partially await nested promises in JavaScript?

I have to make 3 main API calls (A1, B1 and C1) and 2 auxiliary API calls (A2 and B2). These are their dependencies:

This works but is not the right approach because I don't need to wait for B1 to finish before I can call A2 (or for A1 to finish before I can call B2). Note: trigger() returns a promise.

const a1 = A1.trigger();
const b1 = B1.trigger();

await Promise.all([a1, b1]);
A2.trigger(); // should happen earlier
B2.trigger(); // should happen earlier
C1.trigger();

I guess I could do this:

async function handleA() {
  const a1 = await A1.trigger();
  A2.trigger();
  return a1;
}
async function handleB() {
  const b1 = await B1.trigger();
  B2.trigger();
  return b1;
}

await Promise.all([handleA(), handleB()]);
C1.trigger();

In this case, it works because I don't need to worry about A2, B2 or C1, otherwise I'd need to start nesting functions and it might get hairy.

Is there a better approach or is this the best way to do it?

Upvotes: 0

Views: 62

Answers (1)

deceze
deceze

Reputation: 521995

The await syntax is to make asynchronous programming behave more like synchronous programming, which makes this interwoven execution unnecessarily hard. It's pretty simple if you forget about await:

const a1 = A1.trigger();
const b1 = B1.trigger();

a1.then(res => A2.trigger(res));
b1.then(res => B2.trigger(res));
Promise.all([a1, b1]).then(res => C1.trigger(res));

Upvotes: 3

Related Questions