Last active
December 28, 2015 00:29
-
-
Save tastywheat/439948a527154beedce5 to your computer and use it in GitHub Desktop.
process n number of async functions in order. used when promises aren't viable e.g. cross file or service calls.
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
//process n number of async functions in order. used when promises aren't viable e.g. cross file or service calls. | |
var TaskQueue = function(){ | |
var queue = [], | |
isProcessingQueue = false, | |
commonState = { task: 0 }; | |
function add(fn){ | |
queue.push(fn); | |
if(!isProcessingQueue) | |
next(); | |
} | |
function next(err){ | |
if(err) | |
throw new Error(err); | |
var fn = queue.shift(); | |
if(fn){ | |
isProcessingQueue = true; | |
fn(commonState, next); | |
} | |
else | |
isProcessingQueue = false; | |
} | |
return { | |
add: add | |
}; | |
}(); | |
function doWork(commonState, next){ | |
commonState.task++; | |
console.log('Starging something async:' + commonState.task); | |
setTimeout(function(){ | |
console.log('Completed async task: ' + commonState.task); | |
next(); | |
}, 2000); | |
} | |
TaskQueue.add(doWork); | |
TaskQueue.add(doWork); | |
TaskQueue.add(doWork); | |
/* OUTPUT | |
Starging something async:1 | |
Completed async task: 1 | |
Starging something async:2 | |
Completed async task: 2 | |
Starging something async:3 | |
Completed async task: 3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment