Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$q promise with Underscore _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..

So...

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

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.

like image 413
Jon Z Avatar asked Sep 04 '14 17:09

Jon Z


People also ask

What does _ each do?

each. The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.

How do you use underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What is underscore template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering.


1 Answers

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);
like image 83
Bergi Avatar answered Sep 27 '22 19:09

Bergi