'var'数据在其他回调函数中不可读

时间:2019-10-31 09:06:59

标签: javascript node.js


我可以在一个回调函数中保存和读取'var'变量,但是在其他回调中,我无法读取它们。他们成为“ NaN”。如何使这些“ var”在任何地方都可以读取?


我有一个Web服务器,它由两个Android设备连接。一个是发送者,另一个是接收者。

每个设备都连接到服务器并获取其ID。此外,服务器将其ID保存到:

var senderId;
var receiverId;

这些Id变量已保存,可以在其回调函数中读取, 但是当我使用另一个回调函数时,服务器无法读取这些ID变量。它们只是“ NaN”,也无法解析。

您能提供一些有关使变量始终保存数据的建议吗?

这是我的NodeJS代码:

const express = require('express'),
    http = require('http'),
    app = express(),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

var senderId = 0;
var receiverId = 0;
// ...

io.on('connection', (socket) => {
    console.log('user connected.');

    //so here is setting the ID variables
    //receiving a username and if he is a receiver, save he's id to receiverId

    socket.on('join', function (userNickname) {
        if (userNickname == 'receiver') {
            // ...
            receiverId = socket.id; //save he's receiverId
        }
    };

    if (userNickname == 'sender') {
        // Similiar as reciever
        senderId = socket.id; //save he's senderId
    }

    // I can read senderId, receiverId well here
    console.log('receiver socket id :' + receiverId);
    console.log('sender socket id :' + senderId);
    // These Id looks like G0s5Vy-E5f01-JxUAAAD ...
});

// But when I use another call back function, these ID variables are not able to read!

socket.on('send_ytsc', function () {
    console.log("receiver id :" + receiverId);
    console.log("sender id: " + senderId);
    // These Id returns 'NaN', even though I use String(receiverId)
});

0 个答案:

没有答案