Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to pass resolved promise values down to a final "then" chain [duplicate]

I'm trying to get my head around promises, using the Q module in node.js, however I have a small issue.

In this example:

ModelA.create(/* params */) .then(function(modelA){     return ModelB.create(/* params */); }) .then(function(modelB){     return ModelC.create(/* params */); }) .then(function(modelC){      // need to do stuff with modelA, modelB and modelC  }) .fail(/*do failure stuff*/); 

The .create method returns a promise then in each .then(), as expected one gets the resolved value of the promise.

However in the final .then() I need to have all 3 previously resolved promise values.

What would be the best way to do this?

like image 907
MoSs Avatar asked Sep 17 '13 12:09

MoSs


People also ask

Can promise be chained?

Introduction to the JavaScript promise chainingThe callback passed to the then() method executes once the promise is resolved. In the callback, we show the result of the promise and return a new value multiplied by two ( result*2 ).

How do you resolve a promise then?

Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.


1 Answers

These are some of your many options:

Behind door 1, use reduce to accumulate the results in series.

var models = []; [     function () {         return ModelA.create(/*...*/);     },     function () {         return ModelB.create(/*...*/);     },     function () {         return ModelC.create(/*...*/);     } ].reduce(function (ready, makeModel) {     return ready.then(function () {         return makeModel().then(function (model) {             models.push(model);         });     }); }, Q()) .catch(function (error) {     // handle errors }); 

Behind door 2, pack the accumulated models into an array, and unpack with spread.

Q.try(function () {     return ModelA.create(/* params */) }) .then(function(modelA){     return [modelA, ModelB.create(/* params */)]; }) .spread(function(modelA, modelB){     return [modelA, modelB, ModelC.create(/* params */)]; }) .spread(function(modelA, modelB, modelC){     // need to do stuff with modelA, modelB and modelC }) .catch(/*do failure stuff*/); 

Behind door 3, capture the results in the parent scope:

var models []; ModelA.create(/* params */) .then(function(modelA){     models.push(modelA);     return ModelB.create(/* params */); }) .then(function(modelB){     models.push(modelB);     return ModelC.create(/* params */); }) .then(function(modelC){     models.push(modelC);      // need to do stuff with models  }) .catch(function (error) {     // handle error }); 
like image 148
Kris Kowal Avatar answered Sep 23 '22 04:09

Kris Kowal