如何在socket.io连接函数内部执行具有指定参数的函数

时间:2018-10-30 16:53:24

标签: javascript node.js socket.io callback

在我的node.js应用程序中,我需要一些有关回调的帮助。我正在使用socket.io来发射数据。我需要使用io.on('connection')括号之外的方法来创建具有发射和特定参数的函数。我仅在稍后在应用程序中计算参数时才需要触发该内部函数。我该怎么办?

示例代码:

io.on('connection', (socket) => {
    function name(param)
    {
        socket.emit('name', param);
    }
    //rest of the socket.io code
}

//function that calculates the param to be executed above^
function()
{
    var param = somevalue;
    //How can i execute function that is in io.on brackets and pass the param to it from here?
}

3 个答案:

答案 0 :(得分:1)

您可以将io的返回值分配给变量,并在需要时使用它发出事件。像这样:

var socket = io('http://localhost');
socket.on('connect', function(){});
socket.on('disconnect', function(){});

io.on('event', (socket) => {
    getParam();
}

function name(param) {
    socket.emit('name', param);
}

function getParam()
{
    var param = somevalue;
    name(param);
}

答案 1 :(得分:1)

您可以像这样从.on事件中调用函数:

io.on('connection', (socket) => {
    var calculatedParam = calParam(param); //Assuming param exists in the current context...
    socket.emit('name', calculatedParam);
    //rest of the socket.io code
}

//function that calculates the param to be executed above^
function calParam(p)
{
    var calcP = p; //Obviously calculate something here...
    return calcP;
}

答案 2 :(得分:0)

io.on('connection', (socket) => {
    // 10 is "param" in Hello
    Hello(10, function(result){
        console.log("Result from Hello function: " + result);

        // you have still access to socket

    });
}

function Hello(param, callback)
{
    // code etc
    var result = param + 1;

    callback(result);
}