Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with promises in loop?

This is what I would like to do

var response = [];

Model.find().then(function(results){
   for(r in results){
      MyService.getAnotherModel(results[r]).then(function(magic){
          response.push(magic);
      });          
   }
});

//when finished
res.send(response, 200);

however it returns just [] because the async stuff is not ready yet. I am using sails.js that uses Q promise. Any ideas how to return a response when all async calls are finished?

https://github.com/balderdashy/waterline#query-methods (promise methods)

like image 243
UpCat Avatar asked Dec 20 '13 14:12

UpCat


People also ask

How do I resolve Promises before returning?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

Can you resolve a promise multiple times?

No. It is not safe to resolve/reject promise multiple times. It is basically a bug, that is hard to catch, becasue it can be not always reproducible.

How does promise work in event loop?

A promise represents the completion of an asynchronous function. It is an object that might return a value in the future. It accomplishes the same basic goal as a callback function, but with many additional features and a more readable syntax.


1 Answers

Since waterline uses Q, you can use the allSettled method.
You can find more details on Q documentation.

Model.find().then(function(results) {
  var promises = [];
  for (r in results){
    promises.push(MyService.getAnotherModel(results[r]));
  }

  // Wait until all promises resolve
  Q.allSettled(promises).then(function(result) {
    // Send the response
    res.send(result, 200);
  });
});
like image 79
Florent Avatar answered Nov 10 '22 01:11

Florent