Skip to content

Instantly share code, notes, and snippets.

@neilk
Last active January 3, 2016 13:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilk/8467412 to your computer and use it in GitHub Desktop.
Save neilk/8467412 to your computer and use it in GitHub Desktop.
implementations of looping with Bluebird promises
// promisey foreach loop
'use strict';
var Promise = require('bluebird'),
promiseWhile = require('./promiseWhile');
/**
* Promisey foreach
*
* @param {Array} arr
* @param {Function} action which acts on element of arr, returns Promise
* @param {Function} errorHandler see promiseWhile
* @return {Promise}
*/
function promiseForEach(arr, action, errorHandler) {
var i = 0;
var condition = function() {
return i < arr.length;
};
var actionIterator = Promise.method(function() {
var val = arr[i];
i++;
return action(val);
});
return promiseWhile(condition, actionIterator, errorHandler);
}
module.exports = promiseForEach;
// promisey while loop with promisey conditionals
// (so, your condition can potentially do I/O)
'use strict';
var Promise = require('bluebird');
/**
* Promisey while
* @param {Function} condition function returning boolean, or function generating a similar Promise
* @param {Function} action function which takes no args, returns promise
* @param {Function} errorHandler optional - capture errors during looping, return if should continue iterating. Default to terminate
* @return {Promise}
*/
function promiseWhile(condition, action, errorHandler) {
// default errorhandler terminates on first error
if (typeof errorHandler === 'undefined') {
errorHandler = function() { console.log("errorHandler"); return false; };
}
var promiseCondition;
if (Promise.is(condition)) {
promiseCondition = condition;
} else {
promiseCondition = Promise.method(condition);
}
return new Promise(function(resolve, reject) {
var loop = function() {
return promiseCondition().then(function(shouldContinue) {
if (!shouldContinue) {
return resolve();
} else {
return action().then(loop).catch(function() {
if (errorHandler.apply(this, arguments)) {
return loop();
} else {
return reject();
}
});
}
});
};
// first time
process.nextTick(loop);
});
}
module.exports = promiseWhile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment