Skip to content

Instantly share code, notes, and snippets.

@hayeah
Created January 12, 2015 06:40
Show Gist options
  • Save hayeah/dfd39e45dc933a98fb25 to your computer and use it in GitHub Desktop.
Save hayeah/dfd39e45dc933a98fb25 to your computer and use it in GitHub Desktop.
async example
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