Last active
August 29, 2015 13:56
-
-
Save chemdemo/9155713 to your computer and use it in GitHub Desktop.
async queue
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
/** | |
example: | |
function async(n, callback) { | |
setTimeout(function() { | |
callback(n); | |
}, n); | |
} | |
queue([100, 200], async, function(err, r) {console.log(r);}); // => [100, 200] | |
**/ | |
function queue(arr, iterator, ignoreErr, callback) { | |
var aLen = arguments.length; | |
var result = []; | |
var len = arr.length; | |
var i = 0; | |
if(aLen < 3) throw Error('callback required'); | |
if(aLen === 3) { | |
callback = ignoreErr; | |
ignoreErr = false; | |
} | |
function next() { | |
if(i < len) { | |
iterator(arr[i], function(err, r) { | |
if(err && !ignoreErr) { | |
callback(err, result); | |
} else { | |
result[i++] = r; | |
next(); | |
} | |
}); | |
} else { | |
callback(null, result); | |
} | |
}; | |
next(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment