Nodejs Promise.all () always allows

I am new to promises. I am trying to ping some machines to check if they are active. I use my own NodeJS promises. My ping function:

function ping(addr) {
    return new Promise(function(resolve, reject) {
        var args = ['-n', '1', '-w', '5000'];
        args.push(addr);
        var ls = cp.spawn('ping.exe', args);

        ls.on('error', function (e) {
            reject(Error('There was an error while executing the ping'));

        });

        ls.on('exit', function (code) {
            if(code === 0) {
                resolve({host: addr});
            } 
            else {
                reject(Error(addr + " is  down!"));
            }

        });
    });

}

Now I have the details of the machines in an array read from JSON:

gulp.task('pingNodes', ['readConfigJSON'], function () {

    var batches = ConfigJSON.NodeDetails.Batch1.concat(ConfigJSON.NodeDetails.Batch2);
    var pingPromises = batches.map(function (host) {
        return ping(host.Name)
            .then(function (res) {
                console.log(res.host + " is  up!");
            }).catch(function (err) {
                console.log(err);
            });
    });
    return Promise.all(pingPromises).then(function(){console.log("All nodes are up!")});
});

Now it does not deviate, even if some of the node are not available:

[16:58:46] Starting 'init'...
Starting Deployment
[16:58:46] Finished 'init' after 135 ยตs
[16:58:46] Starting 'readConfigJSON'...
[16:58:46] Finished 'readConfigJSON' after 204 ยตs
[16:58:46] Starting 'pingNodes'...
machine1 is  up!
machine2 is  up!
machine3 is  up!
[Error: machine4 is  down!]
All nodes are up!
[16:58:49] Finished 'pingNodes' after 2.54 s
+4
source share
1 answer

Decision

To fix this problem, repeat the error in the handler catch, for example

}).catch(function (err) {
    console.log(err);
    throw err;
});

or remove the handler catch. Basically, you should let the failure flow along the chain, so that it Promise.allgets a rejected promise if the machine does not work.


Basic concepts

  • then catch Promise , .

  • Promise , , , .

, , ,

}).catch(function (err) {
    console.log(err);
});

catch , . , Promise.all Promise, . , , .

var a = Promise.resolve(1)
    .then(function (e) {
        throw e;
    })
    .catch(function (e) {
        // This is what you are doing if the machine is down
        console.log(e);

        // No rejection here, so `then` will be called.
        // Uncomment the throw to see 
        // throw e;
    });

a.then(function (e) {
    console.log("Inside then")
});

a.catch(function (e) {
    console.log("Inside catch")
});

+5

All Articles