Reinitiate reconnect after manually connect #4075
-
Hi all, I'm creating a function that emits a request to the socket, but before it does that, I want to make sure there's a connection. If not, try to connect first with feedback if it succeeded. So I have the following code (simplified version): if (socket.disconnected === true) {
await new Promise<void>((resolve, reject) => {
socket.io.connect((err) => {
if (err) {
return resolve(new Error('Could not connect to socket');
}
return resolve();
});
});
}
socket.emit('message', data, callback); Everything works as expected. An error is triggered when it couldn't connect for some reason, and if it did succeed, the However, if the connection is lost again with the server (I kill the socket.io server for instance), it won't reconnect again if the Any way to accomplish this? Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To answer my own question (been struggeling with this for hours yesterday), I've added a timeout on the finally of the promise (because no matter if there's an error or not, I want the reconnect to again after trying), which triggers the await new Promise<void>((resolve, reject) => {
socket.io.connect((err) => {
if (err) {
return resolve(new Error('Could not connect to socket');
}
return resolve();
});
}).finally(() => setTimeout(() => socket.connect(), 200)); It seems like that does the trick. Directly invoking |
Beta Was this translation helpful? Give feedback.
To answer my own question (been struggeling with this for hours yesterday), I've added a timeout on the finally of the promise (because no matter if there's an error or not, I want the reconnect to again after trying), which triggers the
socket.connect
, like this:It seems like that does the trick. Directly invoking
socket.connect
doesn't work, but with a small timeout it does. Don't know if this is expected behaviour, but for now it does the j…