I'm trying to access a variable in a required node file. However the file requiring it always continues without waiting for the variable to be set. How do I get app.coffee to wait before continuing?
I have two 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 to 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 to retrieve albums.")
return
else
records = data
)
console.log(records)
module.export = records
and app.coffee:
db = require('./db')
console.log(db)
When I run app.coffee I get an output of [] from the console log in app, then the output from db.coffee, even though the require call.
Whats the best way to get for app to wait for db to complete before continuing so I can access the record variable in db.coffee. Thanks for your help.