0

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.

NNNNNNNNNNDelicious
  • 933
  • 3
  • 7
  • 19
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Aaron Dufour Jun 20 '15 at 01:45

1 Answers1

1

In a sense db.coffee has completed. All the code inside that file has been executed.

It's just that what you want, records isn't available yet because the function responsible for getting it, albums.find takes a third argument (err, data), which is a function and it's called much later when the mongoose has actually found your records in the database. It's a disk operation and so this is where Nodejs's asynchronous nature shines, in that it enabled you to "move on" and continue execution of other things while mongoose was fetching the said data.

So in reality, you don't wanna depend on db.coffee being completed, what you actually wanna wait for is for your albums.find function to have called the callback you passed it as the third argument - (err, data)

It would make more sense to export albums itself from your db.coffee rather than records.

albums = mongoose.model('albums', schema)
module.export = albums;

And then in your app.coffee you'd do the fetching/finding records:

albums = require('./db')
albums.find({}, {}, (err, data) ->
    if err?
        console.log("Error: failure to retrieve albums.")
        return
    else
        console.log(records)
);
laggingreflex
  • 32,948
  • 35
  • 141
  • 196