$ q承诺使用Underscore _each

Jon*_*n Z 5 promise underscore.js angularjs angular-promise

所以我在angularjs服务器中有一个方法,它调用一个方法,为数组中的每个方法返回一个promise.我使用下划线_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);
}
Run Code Online (Sandbox Code Playgroud)

这当然不起作用..循环完成并在为每个项目完成makeStuffCooler之前调用'ShowAllMyCoolStuff'.那么..与异步方法交互的正确方法是什么,所以我的ShowAllMyCoolStuff方法将等到集合被填充?这可能是我缺乏$ q和承诺的经验,但我被困住了.提前致谢.

Ber*_*rgi 8

你想要使用$q.all,它需要一系列的承诺.因此,使用map代替each,并将结果传递给$q.all(),这将为您提供等待所有这些的承诺.您甚至不需要stuff手动填充的数组,但只能使用该新承诺的分辨率值.

function processCoolStuff(coolStuffs) {
    return $q.all(_.map(coolStuffs, makeStuffCooler));
}
processCoolStuff(…).then(showAllMyCoolStuff);
Run Code Online (Sandbox Code Playgroud)

  • 很好,谢谢.这正是我所需要的......我认为它与$ q.all有关..还有+1关于摆脱手动填充的数组. (2认同)