[英]node.js - combine callback result
我是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();
您可以从文档中“承诺”执行调用
const util = require('util');
const exec = util.promisify(require('child_process').exec);
更新您的ping函数以返回承诺
function doThePing(ipaddy){
return exec("ping " + ipaddy);
}
然后将所有产生的承诺包装在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.