我是 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/