Created
December 6, 2011 09:54
-
-
Save usefulthink/1437602 to your computer and use it in GitHub Desktop.
simple queueing of async-functions
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
var _queue = []; | |
function enqueue(data, itemProcessor, callback) { | |
for(var i=0, n=data.length; i<n; i++) { | |
(function(item) { | |
_queue.push(function(next) { | |
itemProcessor(item, function() { | |
window.setTimeout(next, 0); | |
}); | |
}); | |
} (data[i])); | |
} | |
return function next() { | |
(_queue.shift() || callback || function() {}) (next); | |
}; | |
} | |
// sample-usage: | |
function async1(item, callback) { | |
console.log('async1: start processing item ' + item); | |
window.setTimeout(function() { | |
console.log('async1: completed processing item ' + item); | |
callback(); | |
}, 500); | |
} | |
function async2(item, callback) { | |
console.log('async2: start processing item ' + item); | |
window.setTimeout(function() { | |
console.log('async2: completed processing item ' + item); | |
callback(); | |
}, 500); | |
} | |
var tbd = ['a', 'b', 'c', 'd', 'e', 'f']; | |
var runQueue = enqueue([1,2,3,4], async1, function(next) { | |
console.log("queue-run finished."); | |
if(0 == tbd.length) { | |
console.log("all done. quit."); | |
return; | |
} | |
var remaining = tbd.splice(0,3); | |
enqueue(remaining, async2); | |
next(); | |
}); | |
runQueue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment