gpt4 book ai didi

javascript - 在循环中等待 Promise

转载 作者:行者123 更新时间:2023-11-28 13:03:52 24 4
gpt4 key购买 nike

使用AngularJs,当使用forEach循环时,循环外的变量仍然始终为0:为了解释我的问题,这是我的代码

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

});

});

在forEach之后,当我执行console.log(totald)时,我得到0。但是当我将console.log放入forEach中时,变量totald会增加。

如何解决问题并在 forEach 完成后获得正确的 Totald 值

最佳答案

您可以将每个 Promise 映射为一个列表,并使用 $q.all 等待所有 Promise。

类似这样的事情:

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

关于javascript - 在循环中等待 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48111247/

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