Wednesday, 31 May 2017

Recursive promise failing

Background

I am trying to connect to a machine net.Socket from Node.js. Sometimes the connection is up and I succeed and other time 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});

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?



via Flame_Phoenix

No comments:

Post a Comment