While loop Promise with Parse.Promise

parse promise cloud code while loop tips

On my current project using Parse.com, I've encountered a problem that I have to run a query again and again until a condition is met. I don't know how many times I have to run so this should be a while loop.

After googling on how to implement while loop for promise. I found this article:

http://blog.victorquinn.com/javascript-promise-while-loop

The author of that article implemented using Bluebird Promise library, but I just want to use Parse.Promise, I don't want to add extra lib to my project.

So after reading the Bluebird version, I've rewritten it to use with Parse.Promise:

var promiseWhile = function(condition, body) {  
  var promise = new Parse.Promise();

  function loop() {
    if (!condition()) return promise.resolve();
    body().then(loop, promise.reject);
  }

  loop();

  return promise;
}

Example on how to use it:

// And below is a sample usage of this promiseWhile function
var sum = 0,  
    stop = 10;

promiseWhile(function() {  
  // Condition for stopping
  return sum < stop;
}, function() {
  // Action to run, should return a promise
  var promise = new Parse.Promise();

  // Arbitrary 250ms async method to simulate async process
  // In real usage it could just be a normal async event that 
  // returns a Promise.
  setTimeout(function() {
    sum++;
    // Print out the sum thus far to show progress
    console.log(sum);
    promise.resolve();
  }, 250);

  return promise;
}).then(function() {
  // Notice we can chain it because it's a Promise,    
  // this will run after completion of the promiseWhile Promise!
  console.log("Done");
});

For more explanation on how the above code work, please read: http://blog.victorquinn.com/javascript-promise-while-loop