klonaway
klonaway

Reputation: 479

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 :

Upvotes: 0

Views: 41

Answers (1)

Rob M.
Rob M.

Reputation: 36511

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

Upvotes: 2

Related Questions