2

I got myself stuck in a pyramid of doom using Promises.

I have the following:

  • getA
  • getB
  • getC

getC depends on getB (and getA) that depends on getA.

So I must call them like this

getA(param)
  .then(getB)
  .then(getC)

but, as stated, I need the output of getA as a paramater to getC, so I did this

getA(param)
  .then(function (A) {
    getB(A)
      .then(function (B) {
        getC(A, B)
      });
  });

yes, the pyramid got me... I have brought shame upon my family. Help me regain my honor back.

Yoni Levy
  • 1,562
  • 2
  • 16
  • 35

2 Answers2

0

I think You can do like this.

var S;
getA(param)
.then(function (A) {
    return S = A;
})
.then(getB)
.then(function (B) {
    return getC(S, B);
})
.then(function (C) {
    console.log(C);
});
sohan nohemy
  • 615
  • 5
  • 13
-1

You can use Promise.all to wait for multiple promises :

your pseudo code becomes :

var pa = new Promise(function(){/*function A*/});
var pb = new Promise(function(){
    pa.then(function {/*function B*/}
});
Promise.all([pa, pb]).then(function(){/*function C*/});
Alice Oualouest
  • 836
  • 12
  • 20
  • 1
    You need a `return` before `pa.then` or it won't work. Nice idea using Promise.all, but -1 for promise-constrictor anti-pattern. `getA` etc. already return promises, so there's zero need for constructors. – jib Nov 23 '15 at 00:50
  • Not to mention that you are using the Promise constructor incorrectly. Without calling `resolve` or `reject` the promise will never fulfill. –  Nov 24 '15 at 09:12