简体   繁体   中英

How to get the callback from a socket.io emit and then return it to the parent function

I have a js function called listClients. It makes a socket.io emit request to grab a list of clients from a node.js server which uses fs to read a file and then send the data back to the client through a callback.

I need to return the callback data to the original function so clients can execute the function and use the data which it returns, but it's not working due to the callback being wrapped in it's own function. What's the best way to work around this?

Client:

function listClients() {
    var sender = getCookieData('relay_client_id');

    if (sender) {
        socket.emit('list_relay_clients', sender, (callback) => {
            return callback; //This won't work because it's async
        });

        return callback; //<---- I need it to be here
    }
}

Server:

socket.on('list_relay_clients', function (sender, callback) {
    callback(fetchAllClients());
});

This is more of a basic JS and async execution problem. You have a Async call and your want to return a synchronous output. This is not the right thing to do though. So you should start looking at promises in this case

function listClients() {
    return new Promise( resolve => {
    var sender = getCookieData('relay_client_id');

    if (sender) {
        socket.emit('list_relay_clients', sender, (callback) => {
            resolve(callback)
        });
    }
    });
}

Then the users of the function should call this function in below way

listClients().then(data=>console.log(data))

If they are not interested in waiting like this and they have async/await JS functionality available then they can use

async function clientCode() {
   let clientData = await listClients();
}

If you still further like to make it synchronous read the below article

http://www.tivix.com/blog/making-promises-in-a-synchronous-manner

But since JS is async, a operation which involves a network call, you should try to keep it async, trying to make it a sync one is not a good practice

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