Skip to content

Instantly share code, notes, and snippets.

@mcfedr
Created August 13, 2012 19:39
Show Gist options
  • Save mcfedr/3343534 to your computer and use it in GitHub Desktop.
Save mcfedr/3343534 to your computer and use it in GitHub Desktop.
callback control - simple way to deal with situations when you have lots of callbacks that need to come back together
/**
* count is how many callbacks there are in total
* after to the function to call when all your callbacks have completed
* return a function that you should call to create your callbacks,
* optionally passing an individual callback handler
*/
function cbcontrol(count, after) {
return function(cb) {
return function() {
cb && cb.apply(this, arguments);
if(--count == 0) {
after();
}
};
};
}
var sqlite3 = require('sqlite3'),
db = new sqlite3.Database('::memory::');
function step1() {
var step1ctr = cbcontrol(3, step2),
db.run('CREATE TABLE a', step1ctr());
db.run('CREATE TABLE b', step1ctr());
db.run('CREATE TABLE c', step1ctr());
}
function step2() {
var step2ctr = cbcontrol(2, step3);
db.run('insert into a', step2ctl(function() { console.log(this.lastID); }));
db.run('insert into b', step2ctl(function() { console.log(this.lastID); }));
}
function step3() {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment