public
Created

Some async pattern

  • Download Gist
proof.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var tags = ['tag1', 'tag2', 'tag3'];
 
(function oneIteration() {
var item = tags.shift();
if (item) {
doAsyncJob(item, oneIteration);
} else {
allDone();
}
})();
 
function allDone() {
console.log('all done');
}
 
function doAsyncJob(item, done) {
console.log('async', item);
setTimeout(done, 1000 * Math.random());
}
result.log
1 2 3 4 5
$ node proof.js
async tag1
async tag2
async tag3
all done

try it actually async...


...
function doAsyncJob(item, done) {
  //don't callback right away...
  process.nextTick(function(){
    console.log('async', item);
    setTimeout(done, 1000 * Math.random());
  });
}

Okay... nm.. didn't notice the recursive call in oneIteration...

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.