小编典典

等待所有诺言解决

angularjs

因此,我遇到了多个未知长度的promise链的情况。我希望在处理所有链条后执行一些操作。那有可能吗?这是一个例子:

app.controller('MainCtrl', function($scope, $q, $timeout) {
    var one = $q.defer();
    var two = $q.defer();
    var three = $q.defer();

    var all = $q.all([one.promise, two.promise, three.promise]);
    all.then(allSuccess);

    function success(data) {
        console.log(data);
        return data + "Chained";
    }

    function allSuccess(){
        console.log("ALL PROMISES RESOLVED")
    }

    one.promise.then(success).then(success);
    two.promise.then(success);
    three.promise.then(success).then(success).then(success);

    $timeout(function () {
        one.resolve("one done");
    }, Math.random() * 1000);

    $timeout(function () {
        two.resolve("two done");
    }, Math.random() * 1000);

    $timeout(function () {
        three.resolve("three done");
    }, Math.random() * 1000);
});

在此示例中,我设置了一个$q.all()承诺1,,2和3,这些承诺会在某个随机时间得到解决。然后,我将诺言添加到第一和第三的结尾。我想all在所有链条都解决后解决。这是运行此代码时的输出:

one done 
one doneChained
two done
three done
ALL PROMISES RESOLVED
three doneChained
three doneChainedChained

有没有办法等待连锁解决?


阅读 259

收藏
2020-07-04

共1个答案

小编典典

当所有链条都解决后,我希望所有人解决。

当然,然后将每个链的承诺传递给all()而不是最初的承诺:

$q.all([one.promise, two.promise, three.promise]).then(function() {
    console.log("ALL INITIAL PROMISES RESOLVED");
});

var onechain   = one.promise.then(success).then(success),
    twochain   = two.promise.then(success),
    threechain = three.promise.then(success).then(success).then(success);

$q.all([onechain, twochain, threechain]).then(function() {
    console.log("ALL PROMISES RESOLVED");
});
2020-07-04