简体   繁体   English

如何从socket.io发出获取回调,然后将其返回给父函数

[英]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. 我有一个名为listClients的js函数。 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. 它发出一个socket.io发出请求,从使用fs读取文件的node.js服务器中获取客户端列表,然后通过回调将数据发送回客户端。

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. 这更多是基本的JS和异步执行问题。 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 如果他们对这样的等待不感兴趣,并且具有异步/等待JS功能,则可以使用

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 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 但是,由于JS是异步的(涉及网络调用的操作),因此您应尝试使其保持异步,尝试使其保持同步不是一个好习惯

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

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