javascript - node.js - 合并回调结果

标签 javascript node.js

我是 Node 新手,对异步编程有些头疼。 我有一个简单的脚本 ping 我的网络上的设备。 现在我想构建以下内容:如果其中一台设备在网络上,那么我如何处理回调,以便仅在所有 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();

最佳答案

您可以“Promisify”执行调用,取自文档

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

更新您的 ping 函数以返回 promise

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

然后将所有生成的 Promise 包装在 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
});

关于javascript - node.js - 合并回调结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46823640/

相关文章:

c# - 如何使按钮不显示但仍被javascript使用?

javascript - 将 json 合并到另一个 json 作为子文档

mysql - AWS 的 NodeJS 部署容量规划

node.js - HTTP.get 请求卡在重定向循环中

javascript - fs.createWriteStream on error 事件不会捕获错误

javascript - 仅使用 nodejs/javascript 从私钥 pem 中提取公钥

javascript - 删除扩展程序的权限

javascript - 删除/隐藏表的空列,包括 <th>

javascript - 如何在 jQuery 中获取表单费用的最后一个值

javascript - 写入 JSON 文件(使用 Node.js 在本地主机服务器上工作)