$ q promise with Underscore _each

So, I have a method on the angularjs server that calls a method that returns a promise for each method in the array. I am using underscore _each to loop through an 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 ends and calls "ShowAllMyCoolStuff" before makeStuffCooler is executed for each item. So .. What is the correct way to interact with the async method, so will my ShowAllMyCoolStuff method wait until the collection is full? This may be my lack of experience with $ q and promises in general, but I'm stuck. Thanks in advance.

+5
source share
3 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 awaits them all. You don't even need this stuff array, which is manually populated, but just can use the resolution value of this new promise.

 function processCoolStuff(coolStuffs) { return $q.all(_.map(coolStuffs, makeStuffCooler)); } processCoolStuff(…).then(showAllMyCoolStuff); 
+8
source
 $q.all([promise1,promise2,promise3,etc]) .then(function(results){ alert("This alert will happen after all promises are resolved."); }) 
0
source

After I read the question and the corresponding answer, I got on the right path. Thanks, bye! But for the final working permit, I spent another hour for all working cases to work. Therefore, I would like to share an example of code that contains a chain of promises, including an array of promises, to wait for permission.

Use case history - this is importing a server-side file (nodeJs) after loading. I used promises to return the corresponding status and http result.

 readFile: function (fileName) { if (fileName) { var deferred = Q.defer(); var self = this; converter({input: fileName}, function (error, userData) { if (error) { deferred.reject(error); } self.storeUsers(error, userData) .then(function (success) { if (success) { deferred.resolve(success) } }) .fail(function (error) { deferred.reject(error) }); }); return deferred.promise; } }, storeUsers: function (error, data) { return Q.all(_.map(data, function (users, emailAddress) { var deferred = Q.defer(); userRepository.findUserByEmail(emailAddress, function (user) { //... user.save(function (error) { if (error) { deferred.reject(error); } else { deferred.resolve(emailAddress); } }); }); return deferred.promise; })); } 

Hope this helps too!

Cheers Ben

0
source

Source: https://habr.com/ru/post/1201843/


All Articles