[英]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.