【问题标题】:Wait on all promises in a promise chain等待承诺链中的所有承诺
【发布时间】:2015-10-30 13:11:32
【问题描述】:

有没有办法等待 Promise 链中的所有承诺?我发现了 Promise.all() 函数用于等待一系列承诺,但我无法做到这一点。

我有一个大概是这样的

var returnPromise2;
var returnPromise1 = function1ThatReturnsAPromise.then(
    function onSuccess(array) {
       console.log("First function finished");
    }).then( function (value) {
          returnPromise2 = function2ThatReturnsAPromise(value);
    });
    return [returnPromise1, returnPromise2];

所以在我的调用代码中,如果我执行Promise.all(arrayOfPromises),我能够从returnPromise1 中获取值,但不是第二个。困境是在返回时,returnPromise2 仍然为空。

有关如何处理此问题的任何提示。

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    当在 .then() 处理程序中时,如果您希望它被链接到链中并使其值成为已实现的值,则必须返回一个 Promise。

    虽然从你的问题中我并不完全清楚你想要实现什么,但似乎你想要做的是:

    function1ThatReturnsAPromise().then(function(array) {
       console.log("First function finished");
       return array;
    }).then(function(value) {
          return function2ThatReturnsAPromise(value);
    }).then(function(finalValue) {
        // you can process the finalValue here which will be the last
        // value returned or the fulfilled value of the last promise returned
    });
    

    如果您想从多个 Promise 中累积值,那么有几种不同的设计模式。以下是先前的答案,展示了几种不同的方法。

    Chaining Requests and Accumulating Promise Results

    How do I access previous promise results in a .then() chain?

    【讨论】:

    • 添加了对显示如何累积结果的其他答案的引用。
    • 谢谢,我会试一试,如果这不是我想要做的,请重新提出问题。
    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 2014-03-12
    • 2020-03-26
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2020-04-22
    相关资源
    最近更新 更多