【发布时间】:2015-06-20 08:57:52
【问题描述】:
我正在尝试访问所需节点文件中的变量。但是,需要它的文件始终会继续运行,而无需等待设置变量。如何让 app.coffee 在继续之前等待?
我有两个文件:
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
和 app.coffee:
db = require('./db')
console.log(db)
当我运行 app.coffee 时,我会从控制台登录 app 得到 [] 的输出,然后是 db.coffee 的输出,即使调用了 require。
让应用程序在继续之前等待 db 完成的最佳方法是什么,以便我可以访问 db.coffee 中的记录变量。感谢您的帮助。
【问题讨论】:
标签: node.js asynchronous requirejs