我目前正在构建一个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
问题在于脚本执行应该暂停直到pingtest()完成并返回结果。我的目标是console.error()消息,如果此测试失败,则停止脚本。我已经在https://github.com/danielzzz/node-ping上使用async await和其他代码示例进行了尝试,但是不幸的是,此操作未能按预期进行。
答案 0 :(得分:2)
您根本无法从回调返回。您可以利用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);
});
或者,您必须在ping.sys.probe
回调中进行所有操作。
答案 1 :(得分:1)
是的,这是异步流程,您可以使用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()