0

I'm facing an issue in processing some data - i'll explain by sections hopefully its clear:

So I have the following code:

Q.all(userIDsToProcess.map(function(item) {
   return findUserAndAddData(item['option'], item['theID']);
}))
.then(function(){
   cleanUpUnsued();
}

And then this method findUserAndAddData contains 2 for loops kind of like:

var findUserAndAddData = function(oIn, userComingIn) {
  var d = Q.defer();

  for (var r=0; r<SomeValue; r++) {
      for (var x=0; x<SomeValue; x++) {
         //Do some processing
      }
  }

  return d.promise;
}

Now the issue I am facing is for each item I send through the Q.all map to that function I want it to be completely processed before the next one is passed.

I thought return d.promise would do this however after some debugging I can see it is not.

So the question - how do I send each item to the findUserAndAddData method to be processed one by one - from my debugging I can see they are all sent in one go (to maintain async behaviour)?

Hope that makes sense - any help would be appreciated.

Thanks.

userMod2
  • 8,312
  • 13
  • 63
  • 115
  • Returning promises does not make asynchronous code magically synchronous, nor does it make `map` wait promise objects before continuing the iteration – Bergi Jun 22 '16 at 21:25
  • Yes - thats what I'm now discovering. Any suggestions on how to make it run synchronously - I still need it to complete before going into the then block with `cleanUpUnsued` – userMod2 Jun 22 '16 at 21:27
  • Have a look at https://stackoverflow.com/questions/18386753/how-to-sequentially-run-promises-with-q-in-javascript/18387432 – Bergi Jun 22 '16 at 21:38
  • Thanks for that direction @Bergi however I;m still a little unclear. In that answer you say they need to push `function(){ return getDelayedString(str); }` so you mean to say it needs to a be a function that is pushed? – userMod2 Jun 22 '16 at 21:48
  • Yes. `function() { return findUserAndAddData(item['option'], item['theID']); }` in your case – Bergi Jun 22 '16 at 21:54
  • I can't get this to work - So using the `Q()` at the end is that the same as `Q.all(userIDsToProcess.map(function(item) { return userIDsToProcess.reduce(function() { return findUserAndAddData(item['option'], item['theID']) } ) })). then(function(){cleanUpUnused()}` – userMod2 Jun 22 '16 at 22:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/115353/discussion-between-usermod2-and-bergi). – userMod2 Jun 22 '16 at 23:02

0 Answers0