0

I want to pass a parameter to a then that is calculated from the information retrieved from a Promise in the middle of my chain.

I have code that looks like this:

myPromise = new Promise(function(resolve,error){ resolve() });
myPromise
  .then(function(){
    return promiseQuery1();
  })
  // You can pass data by calling a later resolution function with a new promise.
  .then(function(){
    return new Promise(function(resolve,error){
      // Save parameter in a local variable
      var resolve_param;
      anotherPromiseQuery()
      // Generate param from data once query is done
      .then(function(data){
         console.log(data);
         resolve_param = getSomethingFrom(data);
      // And then say your new Promise is complete
       }).then(function(){
         resolve(resolve_param)
       });
     });
    })
  }
  // This uses a param
  .then(function(some_param){
    console.log(some_param);
    return someOtherPromise(some_param);
  })
  .then(function(){
    console.log("Completed!");
  })  

The question is: Is this the best way to do it?

allidoiswin
  • 2,543
  • 1
  • 20
  • 23
  • In your case, a simple `return` to pass it to the callback of the next chained `then` should suffice? Also [avoid the `Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Jun 06 '16 at 00:48
  • 1
    Basically `promiseQuery1().then(anotherPromiseQuery).then(getSomethingFrom).then(someOtherPromise).then(console.log)` – Bergi Jun 06 '16 at 00:50
  • I don't think so. getSomethingFrom does not return a promise, but regular data. This breaks the syncing of my queries. Edit: I lied? Apparently this works! – allidoiswin Jun 06 '16 at 00:51
  • `then` callbacks don't need to return promises - they can, but regular values will simply be forwarded just as well. The sequence of function calls is exactly the same as in the snippet in your question. – Bergi Jun 06 '16 at 00:57
  • Yeah, the reason I made this mistake was I actually had used a printing function in a `then` that didnt return the data it was consuming.... :( – allidoiswin Jun 06 '16 at 01:11

0 Answers0