javascript - Node.js database initalization from multiple modules -
i have 3 modules in project: a,b,c; of them using rethinkdb, requires async r.connect call upon initialization.
i'm trying make call module b command line; however, despite starting r.connect on require(), b couldn't serve this, because rethinkdb haven't loaded time module calls.
in ways might code refactored, such can make sure initializations complete before calling b?
i've tried use closures pass state around modules; however, due r.connect being available async function, take form of:
r.connect( config.rethinkdb, function(err, connection) { rconn = connection; // module requires require("./moduleb")(rconn); require("./modulec")(rconn); ...lotsacode... });
which feels wrong. better suggestions?
you can use promise, , pass connection around. this
r.connect(config.rethinkdb) .then(function(connection) { //do stuff here if want initwholeapp(connection) })
and inside initwholeapp
connection, can put application code.
you can simplify to
r.connect(config.rethinkdb) .then(initwholeapp)
with initwholeapp
function accept argument establish connection.
more that, can run each of query on connection(just ensure close connection) once done query, or using rethinkdb connection pool driver support such https://github.com/neumino/rethinkdbdash or roll own.
Comments
Post a Comment