简体   繁体   中英

node.js - combine callback result

I am new to node and having some headaches with async programming. I have a simple script pinging devices on my network. Now I want to build the following: if one of the devices is on the network then how do I handle the callback so that the decision is only made once all the pings are terminated?

var exec = require('child_process').exec;

function doThePing(ipaddy){
    exec("ping " + ipaddy, puts);
}

function puts(error, stdout, stderr) { 
    console.log(stdout);

    if (error !== null){
        console.log("error!!!!");
    }
    else{
        console.log("found device!")
    }
}

function timeoutFunc() {
    doThePing("192.168....");
    doThePing("192.168....");
    //if all pings are successful then do..
    setTimeout(timeoutFunc, 15000);
}

timeoutFunc();

You could "Promisify" the exec call, taken from the docs

const util = require('util');
const exec = util.promisify(require('child_process').exec);

Update your ping function to return the promise

function doThePing(ipaddy){
  return exec("ping " + ipaddy);
}

Then wrap all the resulting promises in a Promise.all

Promise.all([doThePing("192.168...."),doThePing("192.168....")).then(function(values) {
  // all calls succeeded
  // values should be an array of results
}).catch(function(err) {
  //Do something with error
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM