Created
August 13, 2012 19:39
-
-
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
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
/** | |
* 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(); | |
} | |
}; | |
}; | |
} |
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 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