所以我有一个情况我有一个未知长度的多个承诺链。我希望在处理完所有的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);
});
在这个例子中,我设置了一个$q.all()
的承诺一,二,三将在一些随机时间得到解决。然后我将承诺添加到一个和三个的结尾。我希望all
可以在所有链已解决时解决。下面是我运行此代码时的输出:
one done
one doneChained
two done
three done
ALL PROMISES RESOLVED
three doneChained
three doneChainedChained
有没有办法等待链的解决?
感谢您确认我最可怕的恐惧。现在我必须想出一个办法让最后的承诺大声笑。 –
那有什么问题?你的链是动态构建的吗? – Bergi
准确地说我的问题。我试图动态地创建一个承诺链,然后我想在链完成时做一些事情。 –