1

I'm studying the promises with Nodejs. I've a question about a situation with two nested Q.all.

Q.all(promises1)
   .then(function(res1) {
        var promises2 = <METHOD THAT USE THE RES1>
        Q.all(promises2)
            .then(function(re2) {
                  ...
            })
   })    

The problem is that I need the result of the first Q.all for the second. The promises1 are multiple save function, and I need the objectId of the item saved in the multiple function that I use in the promises2. I'am studying the promises for not having nested function, my question is how can I resolve this nest?

  • I don't understand the goal. res1 is in scope here, right? You can declare these functions at the top level and then just reference them if you're bothered by the nesting. – Casey May 18 '16 at 19:22
  • Excuse I wasn't clear. I will edit the question. –  May 18 '16 at 19:28

2 Answers2

0

You can return a promise from within a then function to continue a chain. Also I want to note that the built in Promise API is supported by node.

Promise.all(promises1)
    .then(res => {
        let promises2 = [];
        return Promise.all(promises2);
    })
    .then(res => {

    });
pizzarob
  • 11,711
  • 6
  • 48
  • 69
-1

how can I resolve this nest?

As always :-) You need to return the promise from the then callback, in this case the one you got with the second Q.all call, and then you can chain your second then invocation to the outer promise:

Q.all(promises1)
.then(function(res1) {
    var promises2 = … // method that uses `res1`
    return Q.all(promises2)
//  ^^^^^^
}).then(function(res2) {
    …
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375