In the code below, Room.find().exec()
has a callback function that produces the variable room
. How can I access that object inside of the nested callback function inside of Player.find.exec()
?
addplayer: function(req, res) {
Room.find(req.param('roomid')).exec(function(err, room) {
if (err) {
console.log(err);
return res.send(err, 404);
} else {
if (req.param('playerid') && req.param('playerid').length > 0) {
console.log("Room found:", room);
Player.find(req.param('playerid')).exec(function(err, player) {
if (err) {
console.log(err);
return res.send(err, 404);
} else {
if (typeof room.players === 'undefined' || !room.players.isArray) room.players = new Array();
room.players.push(player);
room.save();
console.log(player);
return res.send(room, 403);
}
});
} else {
console.log('No player id.');
return res.send('No player id.', 404);
}
}
});
}
This mighty make it easier to see what I am asking about:
room
should still be accessible, even in a nested callback.
The reason why the variable will still be defined after the function has returned is because javascript allows the nested callback to hold references to surrounding variables.