1

How do you access content from a Promise that is in a then() function, accessing it in the next then() function.

My question is roughly explained through the following code.

someRandomPromiseFunction().then(function(theArray) {
  var newProm = _.map(theArray, function(arrayItem) {
    return new Promise(function(resolve, reject) {
      resolve(arrayItem);
    });
  }
  Promise.all(newProm).then(function(theArray) {
    return theArray; // How do I access this in the next then() function
  }).catch(function(err) {
    return err;
  });
}).then(function(theArray) {
  console.log(theArray); // I need to access theArray from the Promise.all HERE
});
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Clay Risser
  • 3,272
  • 1
  • 25
  • 28
  • Might also be interested in [How to chain and share prior results with promises](http://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises/28714863#28714863). – jfriend00 Jul 19 '16 at 19:43

1 Answers1

5

Just return the promise

return Promise.all(newProm)...

When you return a promise within a then() callback the outer promise waits until the inner one resolves/rejects. If the inner promise resolves, then that value is passed onto the next then() callback in the outer promise. Otherwise the reject value is passed to the next fail callback in the outer promise.

new Promise((resolve,reject)=>{
   resolve("Main promise");
}).then(function(){
   return new Promise((resolve,reject)=>{
       resolve();
   }).then(()=>"Stackoverflow");
}).then(function(data){
  console.log("Outer 'then()' data:",data);
});
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87