Created
March 13, 2014 16:04
-
-
Save raineorshine/9531270 to your computer and use it in GitHub Desktop.
Some suggestions for improving the asynchronous part of https://github.com/gdiboulder/d3-gapminder.
This file contains 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
// NOTE: The below is pseudo-code. You may need to make some adjustments to | |
// function signatures to use an asynchronous library like async.js | |
// these functions can be made truly asynchronous by accepting a callback | |
// this is preferrably to daisy chaining them, which is too tight a coupling | |
dv.get.gdp = function(cb) { | |
d3.csv('data/gdp.csv', function(error, data) { | |
dv.setup.massage(data, 'gdp'); | |
cb(error, data); | |
}); | |
}; | |
dv.get.life = function(cb) { | |
d3.csv('data/life.csv', function(error, data) { | |
dv.setup.massage(data, 'life'); | |
cb(error, data); | |
}); | |
}; | |
dv.get.population = function(cb) { | |
d3.csv('data/population.csv', function(error, data) { | |
dv.setup.massage(data, 'population'); | |
cb(error, data); | |
}); | |
}; | |
dv.get.fertility = function(cb) { | |
d3.csv('data/fertility.csv', function(error, data) { | |
dv.setup.massage(data, 'fertility'); | |
cb(error, data); | |
}); | |
}; | |
// then we can call them sequentially | |
db.get.gdb(function(error, data) { | |
db.get.fertility(function(error, data) { | |
db.get.population(function(error, data) { | |
db.setup.withData(); | |
}) | |
}) | |
}) | |
// or use an async library to eliminate all the nested callbacks | |
async.series( | |
[ | |
db.get.gdb, | |
db.get.fertility, | |
db.get.population, | |
], | |
// this 'done' callback has the benefit of consolidating errors | |
// from the previous functions | |
function(err, results) { | |
if(err) { console.log(err); } | |
db.setup.withData(); | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment