【问题标题】:How can i get the value outside the socket.on function in the client side? [duplicate]如何在客户端的 socket.on 函数之外获取值? [复制]
【发布时间】:2020-08-03 15:24:37
【问题描述】:

var 数据返回未定义

这里是代码

var data;
    function my_function(newData) {
        console.log(newData)//Everything is okay here, {name: 'Arnel Cariaga', email: 'sadas@sdfs.sad'}
        data = newData;
    }

    socket.on('hello', function(data) {
        var newData = JSON.stringify(data);
        my_function(newData)
    });
    console.log(data) //I get UNDEFINED HERE

【问题讨论】:

    标签: node.js express socket.io


    【解决方案1】:

    问题是你不能真正做到这一点。一种解决方法是将使用数据的代码封装在 .on 块下。

    socket.on('hello', function(data)
     { var newData = JSON.stringify(data);
     my_function(newData) }
    
    //All the code that needs access to the data
    
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-24
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 2021-08-17
      • 2021-12-01
      相关资源
      最近更新 更多