加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 等待所有promise解决

发布时间:2020-12-17 09:11:59 所属栏目:安全 来源:网络整理
导读:所以我有一个情况,我有多个未知长度的承诺链。我想要一些操作运行时,所有的CHAINS已经处理。这是可能吗?这里是一个例子: app.controller('MainCtrl',function($scope,$q,$timeout) { var one = $q.defer(); var two = $q.defer(); var three = $q.defer(
所以我有一个情况,我有多个未知长度的承诺链。我想要一些操作运行时,所有的CHAINS已经处理。这是可能吗?这里是一个例子:
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);
});

在这个例子中,我为promise 1,2和3设置了一个$ q.all(),它将在随机的时间得到解决。然后我将promise添加到一和三的结尾。我想要所有的链解决后,所有的链解决。这里是我运行这段代码时的输出:

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

有没有办法等待链解决?

I want the all to resolve when all the chains have been resolved.

当然,然后只是通过每个链的承诺到all(),而不是初始的承诺:

$q.all([one.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");
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读