简体   繁体   中英

How can I access a callback variable inside of another nested callback function?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM