Skip to content

Instantly share code, notes, and snippets.

@alessioalex
Last active February 9, 2016 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alessioalex/4db3667e33fa2a569dc0 to your computer and use it in GitHub Desktop.
Save alessioalex/4db3667e33fa2a569dc0 to your computer and use it in GitHub Desktop.
Serially Iterating An Array, Asynchronously
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);
});
}
@alessioalex
Copy link
Author

@alessioalex
Copy link
Author

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