问题描述
我正在尝试使用node.js中的Q模块来了解承诺,但是我有一个小问题。
I'm trying to get my head around promises, using the Q module in node.js, however I have a small issue.
在这个例子中:
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,正如预期的那样得到解决承诺的价值。
The .create method returns a promise then in each .then(), as expected one gets the resolved value of the promise.
然而在最后的.then()中,我需要拥有所有3个先前已解决的承诺值。
However in the final .then() I need to have all 3 previously resolved promise values.
最好的方法是什么?
推荐答案
这些是你的很多选择:
在门1后面,使用reduce来累积结果。
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
});
在门2后面,将累积的模型打包成一个数组,并用传播解压缩。
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*/);
在门3后面,捕获父范围内的结果:
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
});
这篇关于将已解决的承诺值传递到最终“然后”的最佳方法是什么?链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!