exporting a module in a callback function?

别来无恙 提交于 2019-12-12 16:26:52

问题


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;
        })

    })

};


回答1:


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.




回答2:


This is not the best way to solve this problem, because modules are read once synchronously and cached but your code seems to handle requests and responses.

You will want rather export something like this:

var rooms = {};

exports.create = function (req, res, next) {
  Room.create({
    room_name: req.body.roomName
  }).complete(function () {
    Room.find({where: {room_name: req.body.roomName}})
      .success(function (room) {
        res.redirect('rooms/videochat/' + req.body.roomName + '/' + room.room_id);
        rooms[req.body.roomName] = room.room_id;
      });
  });
};

exports.rooms = rooms;

If you are using Express.js, you can register in another place a route like this:

var roomsManager = require('./path/to/the/module');

//handle the create room endpoint
app.post('/room', roomsManager.create);

//get the room_id given a room name:
console.log('the room id of "some room" is:', roomsManager.rooms["some room"]);


来源:https://stackoverflow.com/questions/23353693/exporting-a-module-in-a-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!