在继续执行脚本之前,如何等待函数的结果? [英] How to await the result of a function before continuing with the script?
问题描述
我当前正在构建一个Nodejs脚本,该脚本应与Web服务器和本地网络设备进行交互.为了使程序尽可能可靠,我想做一个简单的ping测试,以检查是否可以访问网络设备.
I'm currently building a Nodejs script which should interact with a web server and a local network device. In order to make the program as reliable as possible I want to do a simple ping test to check if the network device can be reached.
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 ,但不幸的是,这没有按预期进行.
The problem is that the script execution should pause until pingtest() has finished and returned the result. My goal is to console.error() a message and stop the script if this test failed. I already tried it with async await and the other code examples at https://github.com/danielzzz/node-ping but unfortunately this didn't work as expected.
推荐答案
您根本无法从回调中返回.您可以利用Promise.像这样重构代码:
You simply can not return from a callback. You can make use of Promise. Refactor the code like this:
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
回调中进行所有操作.
Or, you have to do everything inside ping.sys.probe
callback.
这篇关于在继续执行脚本之前,如何等待函数的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!