Skip to content

Instantly share code, notes, and snippets.

@pselden
Created January 13, 2012 16:26
Show Gist options
  • Save pselden/1607330 to your computer and use it in GitHub Desktop.
Save pselden/1607330 to your computer and use it in GitHub Desktop.
Async task list that starts to execute immediately as soon as you push it.
function Tasks(){
var totalTasks = 0,
tasksComplete = 0,
taskResults = [],
waiting = false,
self = this;
this.push = function(task){
var taskId = totalTasks;
totalTasks += 1;
task(function(err, result){
onTaskComplete(taskId, err, result);
});
};
function onTaskComplete(taskId, err, result){
taskResults[taskId] = { err: err, result: result };
tasksComplete += 1;
if(waiting && tasksComplete == totalTasks){
onFinish();
}
}
function onFinish(){
self._onFinish(taskResults);
}
this.await = function(callback){
self._onFinish = callback;
if(tasksComplete == totalTasks){
onFinish();
} else {
waiting = true;
}
};
}
var taskList = new Tasks();
taskList.push(function(callback){
setTimeout(function(){ callback(null, 1); }, 100);
});
taskList.push(function(callback){
setTimeout(function(){ callback(null, 2); }, 200);
});
taskList.await(function(results){
console.log(results);
});
// Results: [ {err: null, result: 1}, { err: null, result: 2} ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment