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?
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 ).
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With