KLôN KLôN - 4 months ago 14
Node.js Question

Is it possible to chain .all() instead of using Promise.all()?

I'm working in Node.js with bluebird promises. I wanted to use Promise.all in my chain of promises, and tried this :



request-promise(some_API_call)
.then( (responseBody) => {

// using responseBody to determine N new API calls to make

var arrayPromises = [];

for (var i=0 ; i<N ; i++) {
var newPromise = request-promise(new_API_call_i);
arrayPromises.push(newPromise);
}

return(arrayPromises);

})
.all(arrayPromises)
.then( (arrayResults) => {
// do something
});





Throws me an error :
arrayPromises is undefined
.

The only other way I can think of is :



request-promise(some_API_call)
.then( (responseBody) => {

// using responseBody to determine N new API calls to make

var arrayPromises = [];

for (var i=0 ; i<N ; i++) {
var newPromise = request-promise(new_API_call_i);
arrayPromises.push(newPromise);
}

Promise.all(arrayPromises)
.then( (arrayResults) => {
// do something
});
})





I wonder if :


  • Any of these patterns is correct ?

  • I'm not falling again and again in another anti-pattern : is it correct to nest promise chains in this context ?


Answer

arrayPromises is undefined because it is defined within a callback scope that the following then doesn't have access to. I think you would want to return Promise.all from your initial then and continue the chain from there:

request-promise(some_API_call)
.then( (responseBody) => {

      // using responseBody to determine N new API calls to make

      var arrayPromises = [];

      for (var i=0 ; i<N ; i++) {
            var newPromise = request-promise(new_API_call_i);
            arrayPromises.push(newPromise);
      } 

      return Promise.all(arrayPromises);

})
.then( (arrayResults) => {
    // do something
});
Comments