在回调函数中导出模块? [英] exporting a module in a callback function?
问题描述
有没有一种方法可以导出回调函数中的某些变量?例如,如果我需要在另一个文件中使用room.room_id,该怎么办?我试过module.exports.roomId = room.room_id,但另一个文件中的roomId似乎未定义.谢谢!
is there a way to export some variables that are inside a callback function? for example, if i need to use room.room_id in another file, what should i do? i tried module.exports.roomId = room.room_id but roomId in another file appeared to be undefined.thanks!
var Room = require('../models/database').Room
exports.create = function (req, res) {
Room
.create({
room_name: req.body.roomName
})
.complete(function () {
Room
.find({where: {room_name: req.body.roomName}})
.success(function (room) {
// if(err) console.log(err);
res.redirect('rooms/videochat/' + req.body.roomName + '/' + room.room_id);
console.log("room_id: " + room.room_id);
module.exports.roomId = room.room_id;
})
})
};
推荐答案
您不能那样做,因为模块是同步评估的,并且将来会更改module.exports
.您需要做的是提供一个回调,然后传入值或将回调用作可以成功从导出的属性中读取的指示符.
You can't do it like that because modules are evaluated synchronously and you're mutating module.exports
some time in the future. What you need to do is supply a callback and either pass the value in or use the callback as an indicator that you can successfully read from the exported property.
这篇关于在回调函数中导出模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!