gpt4 book ai didi

angularjs - 等待所有的 promise 得到解决

转载 作者:行者123 更新时间:2023-12-02 09:57:49 25 4
gpt4 key购买 nike

所以我遇到的情况是,我有多个长度未知的 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);
});

在此示例中,我为 promise 一、二和三设置了一个 $q.all(),这些 promise 将在某个随机时间得到解决。然后我将 promise 添加到一和三的末尾。我希望当所有链都被解析后,all 才能解析。这是我运行此代码时的输出:

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.

当然,然后只需将每个链的 promise 传递到 all() 而不是初始 promise :

$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");
});

关于angularjs - 等待所有的 promise 得到解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21759361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com