我有一个具有两个数据库调用的进程,需要按顺序进行。最后,我需要将最后两个响应合并为一个响应。

我正在使用平面承诺链,但我不知道如何返回当前和以前的承诺。

我有这样的事情:

let deferred = Q.Promise();

this.methodA('somevalue')
.then(firstResponse => {
    return this.methodB(firstResponse.prop1);
}).then(secondResponse => {
    return this.methodC(secondResponse.prop2);
}).then(finalResponse => {
    //Here I need firstResponse and secondResponse... meaby wrapped inside finalResponse
    let response = {
        prop1: finalResponse.firstResponse.prop1,
        prop2: finalResponse.secondResponse.prop2
    };
    deferred.resolve(response);
});

return deferred.promise;


PS:这是在TypeScript中。我删除了大量代码来做一个关于我所寻找的简单示例。

最佳答案

您可以返回firstResponse和methodB的结果:

let deferred = Q.Promise();

this.methodA('somevalue')
  .then(firstResponse => {
    return Q.all([this.methodB(firstResponse.prop1), Q(firstResponse.prop1)];
  }).then(secondResponse => {
    return Q.all([this.methodC(secondResponse[0].prop2, Q(secondResponse[1])]);
  }).then(finalResponse => {
    //Here I need firstResponse and secondResponse... meaby wrapped inside finalResponse
  let response = {
    prop1: finalResponse.firstResponse.prop1,
    prop2: finalResponse.secondResponse.prop2
  };
  deferred.resolve(response);
});

return deferred.promise;

08-27 10:39