-
-
Save coderek/62b62b051fc9633e178c to your computer and use it in GitHub Desktop.
simple demonstration. this pattern is used by connect to stack middlewares
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 MiddlewareService = function(){ | |
var stack = [], | |
isProcessingStack = false, | |
commonState = { task: 0 }; | |
function push(fn){ | |
stack.push(fn); | |
if(!isProcessingStack) | |
next(); | |
} | |
function next(err){ | |
if(err) | |
throw new Error(err); | |
var fn = stack.shift(); | |
if(fn){ | |
isProcessingStack = true; | |
fn(commonState, next); | |
} | |
else | |
isProcessingStack = false; | |
} | |
return { | |
push: push | |
}; | |
}(); | |
function doWork(commonState, next){ | |
commonState.task++; | |
console.log('Starging something async:' + commonState.task); | |
setTimeout(function(){ | |
console.log('Completed async task: ' + commonState.task); | |
next(); | |
}, 2000); | |
} | |
MiddlewareService.push(doWork); | |
MiddlewareService.push(doWork); | |
MiddlewareService.push(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