Guest User

Untitled

a guest
Jul 27th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. var Promise = require('bluebird');
  2.  
  3. var promiseWhile = function(condition, action) {
  4. var resolver = Promise.defer();
  5.  
  6. var loop = function() {
  7. if (!condition()) return resolver.resolve();
  8. return Promise.cast(action())
  9. .then(loop)
  10. .catch(resolver.reject);
  11. };
  12.  
  13. process.nextTick(loop);
  14.  
  15. return resolver.promise;
  16. };
  17.  
  18.  
  19. // And below is a sample usage of this promiseWhile function
  20. var sum = 0,
  21. stop = 10;
  22.  
  23. promiseWhile(function() {
  24. // Condition for stopping
  25. return sum < stop;
  26. }, function() {
  27. // The function to run, should return a promise
  28. return new Promise(function(resolve, reject) {
  29. // Arbitrary 250ms async method to simulate async process
  30. setTimeout(function() {
  31. sum++;
  32. // Print out the sum thus far to show progress
  33. console.log(sum);
  34. resolve();
  35. }, 250);
  36. });
  37. }).then(function() {
  38. // Notice we can chain it because it's a Promise, this will run after completion of the promiseWhile Promise!
  39. console.log("Done");
  40. });
Add Comment
Please, Sign In to add comment