Background
I am trying to connect to a machine using net.Socket from Node.js. Sometimes the connection is up and I succeed and other times the connection is down, so I keep retrying.
Objective
I want to write a reconnect
method, that tries to connect to an IP. When it succeeds, it resolves, but if it fails it should keep trying.
Code
const reconnect = function ( connectOpts ) {
return new Promise( resolve => {
connect( connectOpts )
.then( () => {
console.log( "CONNECTED " );
resolve();
} )
.catch( () => {
console.log( "RETRYING" );
connect( connectOpts );
} );
} );
};
const connect = function ( connectOpts ) {
return new Promise( ( resolve, reject ) => {
socket = net.createConnection( connectOpts );
//once I receive the 1st bytes of data, I resolve();
socket.once( "data", () => {
resolve();
} );
socket.once( "error", err => reject( err ) );
} );
};
reconnect({host: localhost, port: 8080})
.then(() => console.log("I made it!"));
Problem
The problem is that when the connection fails, it only tries one more time, and then it blows up!
Question
How do I change my code so that I keep reconnecting every time it fails? PS: It is important that this functionality is asynchronous !