简体   繁体   中英

Socket.io return server response

I have an API like this:

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:

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

 //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); } }); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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