我使用socket.io制作多人游戏,我遇到的问题是服务器返回的所有内容都包含在函数内部。 我试图将数据返回到客户端的全局变量。
<script>
let test = "no";
let socket = io();
socket.on('player',function(data){
test = data;
});
console.log(test); // says no instead of yes
</script>
答案 0 :(得分:0)
socket.on是异步调用,因此
<script>
let test = "no";
let socket = io();
socket.on('player',function(data){
test = data;
**console.log(test);** //say yes and also return it here
});
// console.log(test); // says no instead of yes , will not work as async
</script>