1

I have a couple of code about some logic.

My following code block working as expected so willbeUpdated variable couldn't updated literally in syncronized way.

var willbeUpdated = 1;
anArray.forEach(function(i){
   getPromisedData(i).then(function(d){
       willbeUpdated += d;
   });

});
if (wiillbeUpdated == something) {
  // some logic
}

So question is that, Do I have to create again another promised method for that foreach logic and put outside if logic its then method, will be a best practise, or any other preferable idea in this situation ?

Edit: I asked this question to hear best or better approaches about nested async function handling instead of exact code blocks, thanks.

İlker Korkut
  • 3,129
  • 3
  • 30
  • 51

3 Answers3

2

Use Promise.all().

var willbeUpdated = 1,
    promises = [];
anArray.forEach(function(i){
   promises.push(getPromisedData(i));
});
Promise.all(promises).then(function() {
  // some logic
});
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

I think what you're looking for is to put the if block (willBeUpdated == something) inside the function that the getPromisedData resolves with.

So:

var willbeUpdated = 1;
anArray.forEach(function(i){
   getPromisedData(i).then(function(d){
       willbeUpdated += d;
       if (wiillbeUpdated == something) {
         // some logic
       }
   });

});

Would work out. If you can give me a better idea of what you're trying to do then there may be a better solution.

Richard
  • 1,138
  • 1
  • 6
  • 11
1

q and many other promise libraries can handle promise arrays, and wait for their result.

var q = require('q');
var willbeUpdated = 1;
var todo = [];

anArray.forEach(function(i){
  todo.push(getPromisedData(i).then(function(d) {
    return (willbeUpdated+= d);
  }));
});

q(todo).then(function() {
  if (wiillbeUpdated == something) {
    // some logic
  }      
});
dsdenes
  • 1,025
  • 6
  • 15
  • Your and @Gothdo's answers seems ok, but the problem is not code exactly, for instance, in nested loops It will be ugly pushing promises return values to get its latest value, is this solution the only way? – İlker Korkut Dec 11 '15 at 22:30