Created
February 19, 2014 11:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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