asynchronous - node.js continues execution without waiting for a require to complete. -
i'm trying access variable in required node file. file requiring continues without waiting variable set. how app.coffee wait before continuing?
i have 2 files:
db.coffee:
databaseurl = 'mongodb://localhost/db' mongoose = require('mongoose') mongoose.connect(databaseurl) db = mongoose.connection records = [] db.on('error', console.error.bind(console, 'connection error:')) db.once('open', () -> console.log('connected database: ', databaseurl) ) schema = new mongoose.schema({play_counts: {type: number}, album_name: {type: string }}) albums = mongoose.model('albums', schema) albums.find({}, {}, (err, data) -> if err? console.log("error: failure retrieve albums.") return else records = data ) console.log(records) module.export = records
and app.coffee:
db = require('./db') console.log(db)
when run app.coffee output of [] console log in app, output db.coffee, though require call.
whats best way app wait db complete before continuing can access record variable in db.coffee. help.
in sense db.coffee
has completed. code inside file has been executed.
it's want, records
isn't available yet because function responsible getting it, albums.find
takes third argument (err, data)
, function , it's called later when mongoose has found records in database. it's disk operation , nodejs's asynchronous nature shines, in enabled "move on" , continue execution of other things while mongoose fetching said data.
so in reality, don't wanna depend on db.coffee
being completed, wanna wait albums.find
function have called callback passed third argument - (err, data)
it make more sense export albums
db.coffee
rather records.
albums = mongoose.model('albums', schema) module.export = albums;
and in app.coffee
you'd fetching/finding records:
albums = require('./db') albums.find({}, {}, (err, data) -> if err? console.log("error: failure retrieve albums.") return else console.log(records) );
Comments
Post a Comment