K
K
Kneepy2021-09-24 10:42:30
Socket.io
Kneepy, 2021-09-24 10:42:30

How to return promise in socket io?

There is some event that the backend receives and it already makes database requests, etc., because only one user should see these changes, and not all, that is, the callback to which the data arrives, but these changes do not have time to be written to vuex from - why they are not displayed, so the question is how to make the result of the event be asynchronous and return a promise, maybe the callback will have to be removed, I don’t argue, but I don’t consider a new event for receiving data

// client
socket.emit('event',  /*передаём данные*/ (callback) => /*обрабатываем данные*/)

//server
socket.on('event',  (body, callback) =>  /*вызываем функцию и передаём туда параметры и т.п, именно тут нужно вернуть promise клиенту */ )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-24
@Alexandroppolus

If I understand correctly, then it is necessary that the client can make a request using the socket and wait for a response. Usually the scheme is as follows: the client comes up with some unique id, saves its callback to some map id is passed to the server along with other request parameters. the server, having received the data, sends it along with this id ; the client, having caught such a message, takes the id from it and calls mapCallbacks[id](response), after which it removes mapCallbacks[id] to return exactly the promise, you can do this:
mapCallbacks[id] = (data) => {...}

return new Promise((resp, rej) => {
  mapCallbacks[id] = (error, data) => {
    if (error) {
      rej(error);
    } else {
      resp(data);
    }
  };
});

or, alternatively, inside the promise, make mapCallbacks[id] = {resp, rej} and call the necessary one in the message handler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question