Last active
February 9, 2016 08:59
-
-
Save alessioalex/4db3667e33fa2a569dc0 to your computer and use it in GitHub Desktop.
Serially Iterating An Array, Asynchronously
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
function run(steps, data, done) { | |
// our recursion exit strategy: | |
// no items left? we're done. | |
if (steps.length === 0) { | |
return done(); | |
} | |
// get the first item in the array | |
var step = steps.shift(); | |
// kick it off, here | |
step(data, function(err) { | |
if (err) { return done(err); } | |
// process next items using recursion | |
// keep in mind that steps.shift() removed the 1st fn from the array | |
run(steps, data, done); | |
}); | |
} |
Hmm in fact Derick came up with the same solution in his library: https://github.com/derickbailey/migroose/blob/61b4510584fa222778b666ea997cdca34967cd5c/migroose/stepRunner/index.js#L17-L40
In the snippet above I'm not doing any wrapping of the step function in a setImmediate
because I assume they're all async.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An alternative to the example found here: http://derickbailey.com/2015/03/12/serially-iterating-an-array-asynchronously/