Skip to content

Instantly share code, notes, and snippets.

@chris5marsh
Created February 19, 2014 11:37
Show Gist options
  • Save chris5marsh/9090348 to your computer and use it in GitHub Desktop.
Save chris5marsh/9090348 to your computer and use it in GitHub Desktop.
Run a function on each member of an array (like reduce) but use promises to chain them together asynchronusly
/**
* Makes chain of promises
* @param {function} toRun Function to apply to each item
* @param {array} processArray Array of items to process
* @return {promise} Final promise to pass on
*/
chain: function(toRun, processArray) {
var defer = Q.defer();
var args = Array.prototype.slice.call(arguments).slice(2);
processArray.reduce(function (previous, current) {
return previous.then(function (previousValue) {
return toRun(current, args);
});
}, Q.resolve(true))
.then(function(finalValue) {
console.log(finalValue);
return defer.resolve(true);
});
return defer.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment