0

I'm working in node and must make n amount of API calls after getting n returned from a promise. My initial thought would be to create a foreach loop that creates n promises, store them in an array, and then call

Promise.all(promisesArray).then(function(){...});

However, this would have the be wrapped in the then() call from the original promise, effectively setting up a nested promise situation.

getN() //returns a promise object.
.then(function(n) {
    var promisesArray = [];
    for(var i = 0, i < n; i++) {
        var promise = new Promise(function(resolve, reject) { callSomething(i, resolve) });
        promisesArray.push(promise);

    }
    Promises.all(promisesArray).then(function(){
        ... 
        resolve; //resolves original promise
    });
.then(function(something) {...})
.catch(function(err) {...};

How can I avoid this? Thanks for your help!

mcheah
  • 1,209
  • 11
  • 28
  • 1
    What do you think is wrong with nesting promises? And why not just [unnest that inner `then` call](http://stackoverflow.com/a/22000931/1048572)? – Bergi Apr 27 '17 at 00:31
  • Don't forget to `return` the `Promise.all…` from the `then` callback – Bergi Apr 27 '17 at 00:31
  • Thanks @Bergi, It seemed like most resources I read said that the point of promises is that you don't have to nest anything anymore, so I assumed that it was poor practice to nest like this. Would unnessting the inner `then` call look like: `.then(function(n){ ... return Promises.all(promisesArray); .then(function(values) {...})` ? So it's technically still nested but just looks cleaner? – mcheah Apr 27 '17 at 15:29
  • Nesting is fine and [sometimes necessary](http://stackoverflow.com/a/28250687/1048572), the real [point of promises](http://stackoverflow.com/a/22562045/1048572) is that you still can `return` even from nested callbacks. – Bergi Apr 27 '17 at 15:44
  • 1
    Yes, `getN().then(function(n) { … return Promise.all(…); }).then(…)` is the correct solution, and it's not even technically any nested `then` calls – Bergi Apr 27 '17 at 15:45

0 Answers0