等待循环中的诺言 [英] waiting for Promise in a Loop
本文介绍了等待循环中的诺言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用AngularJs,当使用forEach循环时,循环外部的变量仍然总是为0:
来解释我的问题,这是我的代码
var totald = 0;
children.forEach(function(child){
fetchdata(child ['id'])。then(function(resp){
totald + = resp.total;
domaines。 ({'id':child ['id'],'total':resp.total,'details':resp.details});
});
});
在forEach之后,当我做console.log(totald)时,我得到了0.但是当我console.log在forEach中,变量totald递增。
如何解决问题并在forEach完成后得到totald的正确值
解决方案
您可以将每个承诺映射为列表,并使用 $ q.all
类似于这样:
var totald = 0;
var promises = children.map(function(child){
return fetchdata(child ['id'])。then(function(response){
return {id:child ['id '],response:response};
});
});
$ q.all(promises).then(function(results)){
results.forEach(function(result){
totald + = result.response.total;
domaines.push({'id':result.id,'total':result.response.total,'details':result.response.details});
});
};
Using AngularJs, when using a forEach Loop, the variable outside the loop still always 0: to explain my problem, this is my code
var totald=0;
children.forEach(function (child) {
fetchdata(child['id']).then(function (resp) {
totald+= resp.total;
domaines.push({'id': child['id'], 'total': resp.total, 'details': resp.details});
});
});
After forEach, when I do console.log(totald), I get 0. but when I put console.log inside the forEach, the variable totald is incremented.
How I can resolve the problem and get the correct value of totald after the forEach finishied
解决方案
You can map each promise as a list and await all of them using $q.all
.
Something like this:
var totald = 0;
var promises = children.map(function (child) {
return fetchdata(child['id']).then(function(response){
return { id: child['id'], response: response };
});
});
$q.all(promises).then(function(results)){
results.forEach(function(result){
totald += result.response.total;
domaines.push({'id': result.id, 'total': result.response.total, 'details': result.response.details});
});
};
这篇关于等待循环中的诺言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文