Skip to content

Instantly share code, notes, and snippets.

@sbimikesmullin
Last active April 3, 2016 18:21
Show Gist options
  • Save sbimikesmullin/3f1e5b50c7a2b84a68b8 to your computer and use it in GitHub Desktop.
Save sbimikesmullin/3f1e5b50c7a2b84a68b8 to your computer and use it in GitHub Desktop.
Smallest Asynchronous Flow Control implementation in JavaScript
// use like: forEachAsyncSerial(Post.find(), (next, post) => { /* ... */ next(); }, () => { /* done! */ });
static forEachAsyncSerial(a, each_cb, done_cb) {
let i = 0;
const next = () => {
if (i >= a.length || false === each_cb(next, a[i++])) {
if ('function' == typeof done_cb) done_cb();
}
};
process.nextTick(next);
}
static whileAsyncSerial(test, each_cb, done_cb) {
const next = () => {
if (!test() || false === each_cb(next)) {
if ('function' == typeof done_cb) done_cb();
}
};
process.nextTick(next);
}
static ifAsync(/* test, true_fn, args..., done_cb */) {
let args = Array.prototype.slice.call(arguments);
let test = args.shift();
let done_cb = args.pop();
if (test) {
let true_fn = args.shift();
args.push(done_cb);
true_fn.apply(null, args);
}
else {
done_cb();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment