$q 承诺下划线 _each [英] $q promise with Underscore _each

查看:32
本文介绍了$q 承诺下划线 _each的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 angularjs 服务器中有一个方法,它正在调用一个方法,该方法为数组中的每个方法返回一个承诺.我使用下划线 _each 循环遍历数组.我想等到整个数组处理完毕,然后再调用方法中的最后一行代码..

So I have a method in a angularjs server that is calling a method that returns a promise for each method in a array. I am using underscore _each to loop through the array. I want to wait until the entire array is processed before I call the final line of code in the method..

所以...

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 和一般承诺缺乏经验,但我被卡住了.提前致谢.

This of course does not work.. the loop completes and calls 'ShowAllMyCoolStuff' before the makeStuffCooler is done for each item. So.. what is the correct way to interact with the async method so my ShowAllMyCoolStuff method will wait until the collection is populated? This may be my lack of experience with $q and promises in general, but I am stuck. Thanks in advance.

推荐答案

您想使用 $q.all,它接受一组 promise.所以使用 map 而不是 each,并将结果传递给 $q.all(),这会给你一个等待所有他们.您甚至不需要手动填充的 stuff 数组,而只需使用该新承诺的分辨率值即可.

You want to use $q.all, which takes an array of promises. So use map instead of each, and pass the result to $q.all(), which gives you a promise that waits for all of them. You don't even need that stuff array which is manually filled, but just can use the resolution value of that new promise.

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

这篇关于$q 承诺下划线 _each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆