如何在另一个嵌套回调函数中访问回调变量?

时间:2022-05-12 19:55:25

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()?

在下面的代码中,Room.find()。exec()有一个产生变量空间的回调函数。如何在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:

这有力地让我更容易看到我在问什么:

如何在另一个嵌套回调函数中访问回调变量?

1 个解决方案

#1


3  

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.

在函数返回后仍然定义变量的原因是因为javascript允许嵌套回调保存对周围变量的引用。

#1


3  

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.

在函数返回后仍然定义变量的原因是因为javascript允许嵌套回调保存对周围变量的引用。