简体   繁体   English

node.js-合并回调结果

[英]node.js - combine callback result

I am new to node and having some headaches with async programming. 我是Node的新手,并且对异步编程有些头疼。 I have a simple script pinging devices on my network. 我的网络上有一个简单的脚本ping设备。 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? 现在,我要构建以下内容:如果其中一台设备在网络上,那么我该如何处理回调,以便仅在所有ping都终止后才做出决定?

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 更新您的ping函数以返回承诺

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

Then wrap all the resulting promises in a Promise.all 然后将所有产生的承诺包装在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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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