javascript - Javascript - 如何在继续脚本之前等待函数的结果?

我目前正在构建一个Nodejs脚本,该脚本要和Web服务器和本地网络设备进行交互。为了使程序尽可能可靠,我想做一个简单的ping测试,以检查是否可以访问网络设备。


var ping = require('ping');



function pingtest(host) {


 ping.sys.probe(host, function (isAlive) {


 var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';


 console.log(msg);



 return isAlive;


 });


}



let pingSuccessful = pingtest('192.168.178.100');



console.log(pingSuccessful);


console.log('Should not executed before pingtest has finished.');



控制台上的输出如下所示:


undefined


Should not executed before pingtest has finished.


host 192.168.178.100 is dead



我的目标如果测试失败,则停止脚本,然后抛出console.error()

时间:

你不能从回调中返回,你可以使用Promise ,这样重构代码:


function pingtest(host) {


 return new Promise((resolve, reject) => {


 ping.sys.probe(host, function (isAlive) {


 var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';


 console.log(msg);



 resolve(isAlive);


 });


 });


}



pingtest('192.168.178.100').then((pingSuccessful) => {


 console.log(pingSuccessful);


});



这是异步,你可以使用async/await来解决这个问题,


function pingtest(host) {


 return newPromise((res, rej) => {


 ping.sys.probe(host, function (isAlive) {


 var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';


 console.log(msg);


 res(isAlive)


 });


 }


}



const startPing = async () => {


 let pingSuccessful = await pingtest('192.168.178.100');



 console.log(pingSuccessful);


 console.log('Should not executed before pingtest has finished.');


}



startPing()



...