2

My promise chain looks like this:

PromiseA()
.then((A) => PromiseB(A))
.then((B) => PromiseC(B))
...
.then((X) => PromiseY(X))
.then((Y) => PromiseZ(Y, A))

How do I use parameter A in the last promise without drilling through all the promises like so:

PromiseA()
.then((A) => Promise.all[A, PromiseB(A)])
.then(([A, B]) => Promise.all[A, PromiseC(B)])
...
.then(([A, X]) => Promise.all[A, PromiseY(X)])
.then(([A, Y]) => PromiseZ(A, Y))
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Jello
  • 39
  • 3
  • 7
    `async/await` is generally the easiest way to avoid messes like this. – Barmar Feb 02 '23 at 20:54
  • By avoiding promise chains. – Dave Newton Feb 02 '23 at 20:56
  • 1
    I agree `async/await` is the way to go, but all the ways you can share prior results into later spots in the promise chain are discussed here: [How to chain and share prior results with Promises](https://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises/28714863#28714863). – jfriend00 Feb 02 '23 at 21:07

3 Answers3

6

Refactor your function to async/await:

async function fun() {
  const A = await PromiseA();
  const B = await PromiseB(A);
  const C = await PromiseC(B);
  // ...
  const Y = await PromiseY(A, B, C);
  const Z = await PromiseZ(Y, A);
}
AKX
  • 152,115
  • 15
  • 115
  • 172
1

You can nest the chain inside the first .then() callback so that A is still in scope.

PromiseA()
.then((A) => 
    PromiseB(A)
    .then(PromiseC)
    .then(PromiseD)
    .then(PromiseE)
    ...
    .then((Y) => PromiseZ(Y, A)
);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can always use a variable to store it.

let a;
PromiseA()
.then(A => (a = A, PromiseB(A))
.then(B => PromiseC(B))
...
.then(X => PromiseY(X))
.then(Y) => PromiseZ(a, Y));
Redu
  • 25,060
  • 6
  • 56
  • 76