问题描述
我想要一个for循环,该循环在每次迭代时调用异步函数.
I want to have a for-loop which calls async functions each iteration.
在for循环之后,我想执行另一个代码块,但在解决for循环中的所有先前调用之前,不要执行.
After the for-loop I want to execute another code block, but not before all the previous calls in the for-loop have been resolved.
目前,我的问题是,在for循环之后执行的代码块是否在所有异步调用完成之前执行,或者根本不执行.
My problem at the moment is, that either the code-block after the for-loop is executed before all async calls have finished OR it is not executed at all.
带有FOR循环的代码部分及其后的代码块(有关完整代码,请参见小提琴 ):
The code part with the FOR-loop and the code block after it (for complete code, please see fiddle):
[..]
function outerFunction($q, $scope) {
var defer = $q.defer();
readSome($q,$scope).then(function() {
var promise = writeSome($q, $scope.testArray[0])
for (var i=1; i < $scope.testArray.length; i++) {
promise = promise.then(
angular.bind(null, writeSome, $q, $scope.testArray[i])
);
}
// this must not be called before all calls in for-loop have finished
promise = promise.then(function() {
return writeSome($q, "finish").then(function() {
console.log("resolve");
// resolving here after everything has been done, yey!
defer.resolve();
});
});
});
return defer.promise;
}
我创建了一个jsFiddle,可以在这里找到 http://jsfiddle.net/riemersebastian/B43u6/3/.
I've created a jsFiddle which can be found here http://jsfiddle.net/riemersebastian/B43u6/3/.
目前看来执行顺序很好(请参阅控制台输出).
At the moment it looks like the execution order is fine (see the console output).
我的猜测是,这仅仅是因为每个函数调用都会立即返回而无需进行任何实际工作.我试图用setTimeout延迟defer.resolve,但失败了(即最后一个代码块从未执行过).您可以在小提琴的注释框内看到它.
My guess is, that this is simply because every function call returns immediately without doing any real work. I have tried to delay the defer.resolve with setTimeout but failed (i.e. the last code block was never executed). You can see it in the outcommented block in the fiddle.
当我使用写入文件和从文件读取的真实函数时,最后一个代码块在最后一次写操作完成之前执行,这不是我想要的.
When I use the real functions which write to file and read from file, the last code block is executed before the last write operation finishes, which is not what I want.
当然,该错误可能出在其中的一个读/写函数中,但我想验证一下我在此处发布的代码没有问题.
Of course, the error could be in one of those read/write functions, but I would like to verify that there is nothing wrong with the code I have posted here.
推荐答案
您需要使用的是 $ q.all ,它将多个诺言合并为一个诺言,只有当所有诺言都得到解决时,该诺言才能得到解决.
What you need to use is $q.all which combines a number of promises into one which is only resolved when all the promises are resolved.
在您的情况下,您可以执行以下操作:
In your case you could do something like:
function outerFunction() {
var defer = $q.defer();
var promises = [];
function lastTask(){
writeSome('finish').then( function(){
defer.resolve();
});
}
angular.forEach( $scope.testArray, function(value){
promises.push(writeSome(value));
});
$q.all(promises).then(lastTask);
return defer.promise;
}
这篇关于angular $ q,如何在for循环内和执行后链接多个promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!