Created
July 12, 2017 20:23
-
-
Save chamberlainpi/8fa27de19d07821a7c28e165bb1c049f to your computer and use it in GitHub Desktop.
NodeJS AsyncEach for handling async.series-like control-flow on Array of items.
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
const _ = require('lodash'); | |
const trace = console.log.bind(console); | |
function AsyncEach(objList, funcList, cb) { | |
this.objList = objList; | |
this.funcList = _.isArray(funcList) ? funcList : [funcList]; | |
this.cb = cb; | |
this._objID = -1; | |
this._obj = null; | |
this._funcID = -1; | |
this._next = this.next.bind(this); | |
this._each = this.each.bind(this); | |
setTimeout(this._next, 1); | |
} | |
_.extend(AsyncEach.prototype, { | |
next() { | |
if((++this._objID) >= this.objList.length) { | |
return this.cb(); | |
} | |
this._obj = this.objList[this._objID]; | |
//Reset the callback ID before we start iterating on each one: | |
this._funcID = -1; | |
this._each(); | |
}, | |
each() { | |
if((++this._funcID) >= this.funcList.length) { | |
return this._next(); | |
} | |
var func = this.funcList[this._funcID]; | |
func(this._each, this._obj, this._objID); | |
} | |
}); | |
AsyncEach.make = function(arr, onDone, onEach) { | |
new AsyncEach(arr, onDone, onEach); | |
}; | |
module.exports = AsyncEach; | |
//////////////////////////////////////////// | |
AsyncEach.make(["bob", "foo", "bar"], [ | |
(step, item, id) => { | |
trace(`test 1 ${item} #${id}`); | |
setTimeout(step, 500); | |
}, | |
(step, item, id) => { | |
trace(`test 2 ${item} #${id}`); | |
setTimeout(step, 250); | |
} | |
], () => trace("DONE! Toute Finito!") ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment