【发布时间】:2014-10-29 13:46:24
【问题描述】:
所以我在 angularjs 服务器中有一个方法,该方法正在调用一个方法,该方法为数组中的每个方法返回一个承诺。我正在使用下划线 _each 循环遍历数组。我想等到整个数组都处理完后,再调用方法中的最后一行代码..
所以...
function ProcessCoolStuff(coolStuffs)
{
var stuff = [];
_.each(coolStuffs, function(coolStuff)
{
//Some method using $q to return
makeStuffCooler(coolStuff).then(function(coolerStuff)
{
stuff.push(coolerStuff);
});
});
//Maybe Call a Display Method, or call event ect..
ShowAllMyCoolStuff(stuff);
}
这当然行不通。循环完成并在每个项目的 makeStuffCooler 完成之前调用“ShowAllMyCoolStuff”。那么..与异步方法交互的正确方法是什么,所以我的 ShowAllMyCoolStuff 方法将等到填充集合?这可能是我对 $q 和一般承诺缺乏经验,但我被困住了。提前致谢。
【问题讨论】:
-
值得注意的是,如果您的浏览器运行 Angular,您可能可以依靠它来拥有 Array.prototype.forEach 和 Array.prototype.map。但是,是的,$q.all 就是它所在的位置。
标签: angularjs underscore.js promise angular-promise