简体   繁体   English

Socket.io返回服务器响应

[英]Socket.io return server response

I have an API like this: 我有这样的API:

function movePlayer(x, y){
    if (x < 0 || y < 0) return true;
    else return false;
}

and now I want to change only this function so that the if-else is on the server side like this: 现在我只想更改此函数,以便if-else在服务器端如下:

Client side: 客户端:

function movePlayer(x, y){
    var result;
    socket.emit('move_player', {
        _x: x,
        _y: y
    });
    socket.on('move_finished', function(data){
        result = data._result;
    });
    return result;
}

Server side: 服务器端:

var result;
socket.on('move_player', function(data){
    if (data._x < 0 || data._y < 0) result = false;
    else result = true;
    socket.emit('move_finished', {_result: result});
});

But it won't work since the server's response is asynchronous and the client side won't wait to get the response. 但它不起作用,因为服务器的响应是异步的,客户端不会等待获得响应。 So is there any way of doing it by just change the function definition only? 那么有没有办法只通过改变函数定义来做到这一点?

Sorry it's not really good but I'm not a pro of Promise, I hope someone more qualified will come here 对不起,这不是很好,但我不是Prom的专家,我希望有更多合格的人来这里

 //somewhere else aFunction().then((result) => { //do something with this result }) .catch(err => { console.log(err); }) aFunction = function(){ return new Promise((resolve, reject) { //some code that generates your result if (result) { resolve(result); } else { reject(error); } }); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM