将已解决的承诺值传递到最终"然后"链的最佳方法是什么

MoS*_*oSs 26 javascript node.js promise

我正在尝试使用node.js中的Q模块来了解promises,但是我有一个小问题.

在这个例子中:

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*/);
Run Code Online (Sandbox Code Playgroud)

.create方法在每个.then()中返回一个promise,正如预期的那样,获取promise的已解析值.

但是在最后的.then()中,我需要拥有所有3个先前解析的promise值.

最好的方法是什么?

Kri*_*wal 36

这些是您的众多选择中的一部分:

在门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
});
Run Code Online (Sandbox Code Playgroud)

在门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*/);
Run Code Online (Sandbox Code Playgroud)

在门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
});
Run Code Online (Sandbox Code Playgroud)


jus*_*oon 23

蓝鸟承诺库提供通过这个另一种解决方案.bind().

它看起来像这样:

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;
});
Run Code Online (Sandbox Code Playgroud)

文档中有很多关于此方法的有趣信息.