问题
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.');
The output on the console is the following:
undefined
Should not executed before pingtest has finished.
host 192.168.178.100 is dead
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.
回答1:
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);
});
Or, you have to do everything inside ping.sys.probe
callback.
回答2:
yes this is async flow, you can use async/await to solve this issue
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()
来源:https://stackoverflow.com/questions/58681933/how-to-await-the-result-of-a-function-before-continuing-with-the-script