Created
January 12, 2015 06:40
-
-
Save hayeah/dfd39e45dc933a98fb25 to your computer and use it in GitHub Desktop.
async example
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
var n; // a global counter of how many requests hand been processed | |
var a = [1,2,3,4,5,6,7]; | |
// a handler that increments `n`, and print out each element in a. | |
function countHandler(req,res,next) { | |
// these are new for each request, don't need to protect them. | |
var a,b,c; | |
// an asynchronous loop that print out each element in an array | |
var i = 0; // this loop would break if you move it outside of the countHandler scope. | |
function iter() { | |
if(i >= a.length) { | |
return; | |
} else { | |
console.log(a[i]); | |
setTimeout(iter,100); | |
} | |
} | |
setTimeout(iter,100); | |
// in other languages you'll need to lock this, but not in node. | |
n++; | |
next(); | |
} | |
app.use(countHandler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment