Home > Enterprise >  How can I avoid promise chain drilling?
How can I avoid promise chain drilling?

Time:02-03

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))

CodePudding user response:

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);
}

CodePudding user response:

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)
);

CodePudding user response:

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));
  • Related