什么是最好的方式将解决的承诺价值传递给最终的“当时”链

我试图让我的头在承诺,在node.js使用Q模块,但我有一个小问题。

在这个例子中:

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*/); 

.create方法在每个.then()中返回一个promise,如预期的那样获得promise的parsing值。

然而在最后.then()我需要有所有3先前解决的承诺值。

什么是最好的方法来做到这一点?

这些是你的许多select中的一些:

在门1后面,使用reduce来累计结果。

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

在门2后面,将累积的模型打包成一个数组,然后展开。

 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*/); 

在门3后面,捕获父范围的结果:

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

蓝鸟承诺图书馆通过.bind()提供了另一个解决scheme。

它看起来像这样:

 ModelA.create(/* params */).bind({}) .then(function (modelA) { this.modelA = modelA; return ModelB.create(/* params */); }) .then(function (modelB) { this.modelB = modelB; return ModelC.create(/* params */); }) .then(function (modelC) { // you have access to this.modelA, this.modelB and modelC; }); 

在文档中有关于这个方法的很多有趣的信息。

您可能不需要等到创buildmodelA以创buildmodelB等等。
如果这是真的,那么你可以做到以下几点:

 var promises = [ ModelA.create(...), ModelB.create(...), ModelC.create(...) ); Q.all( promises ).spread(function( modelA, modelB, modelC ) { // Do things with them! }).fail(function() { // Oh noes :( }); 

这是做什么的:

  • 创build一个承诺数组,每个模型都有一个承诺;
  • 同时执行所有3个承诺;
  • 所有3个承诺完成后,执行一个在spread()传递的函数。 参数是声明顺序中每个承诺的parsing值。

我希望它可以帮助你:)