Skip to content

Instantly share code, notes, and snippets.

@jordaaash
Last active August 29, 2015 14:05
Show Gist options
  • Save jordaaash/75cb455d28e285276580 to your computer and use it in GitHub Desktop.
Save jordaaash/75cb455d28e285276580 to your computer and use it in GitHub Desktop.
Async while loop
'use strict';
var Promise = require('bluebird'),
slice = Array.prototype.slice,
promiseLoop;
promiseLoop = function (fn, thisArg) {
var argsArray = slice.call(arguments, 2);
return function () {
var pending = Promise.pending(),
tick;
tick = function () {
return fn.apply(thisArg, argsArray)
.then(function (loop) {
if (loop) {
process.nextTick(tick);
}
else {
pending.resolve();
}
})
.catch(pending.reject);
};
process.nextTick(tick);
return pending.promise;
};
};
module.exports = promiseLoop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment