Last active
August 29, 2015 14:24
-
-
Save screeny05/cc6fb576e198c21ff1ab to your computer and use it in GitHub Desktop.
async js fn-queuing
This file contains hidden or 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
async.each = function(toIterate, fn, callback){ | |
var calledCount = 0; | |
for (var i = 0; i < toIterate.length; i++) { | |
fn(toIterate[i], function(err){ | |
if(err){ | |
callback(err); | |
callback = function(){}; | |
return; | |
} | |
calledCount++; | |
if(calledCount >= toIterate.length){ | |
return callback(); | |
} | |
}, i); | |
} | |
}; |
This file contains hidden or 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
async.map = function(toMap, fn, callback){ | |
var mapped = []; | |
async.each(toMap, function(obj, cb, i){ | |
fn(obj, function(err, ret){ | |
if(err){ | |
return cb(err); | |
} | |
mapped.push(ret); | |
return cb(); | |
}, i); | |
}, function(err){ | |
if(err){ | |
return callback(err); | |
} | |
return callback(null, mapped); | |
}); | |
}; |
This file contains hidden or 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
async.queue = function(){ | |
var queue = []; | |
var me = {}; | |
me.queue = function(fn){ | |
queue.push(fn); | |
return me; | |
}; | |
me.exec = function(fn){ | |
var currentFn = 0; | |
var runOne = function(data){ | |
queue[currentFn++](data, function(err, data){ | |
if(err || currentFn < queue.length - 1) return fn(err, data); | |
return runOne(data); | |
}); | |
}; | |
return runOne(); | |
}; | |
return me; | |
} | |
/** | |
* Use like this: | |
* var q = async.queue(); | |
* q | |
* .queue(asyncTask1) | |
* .queue(function(fn){ setTimeout(function(){ fn(null, 'data') }, 500); }) | |
* .queue(asyncTask3) | |
* .exec(function(err, data){ console.log(err, data); })); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment