I am new to node js and currently learning about promises and await/async. I tried the below code but couldn't figure out how to make the code wait till the function hostping is finished. I have also tried promises but couldn't make it wait.
var ping = require('ping');
var hoststatus
var hosts = ['google.com'];
async function test()
{
var connected = await hostping(hosts);
console.log('connected--------------', connected)
connected.then(function(hoststatus) {
console.log('hoststatus--------------', hoststatus)
if (hoststatus == 1) {
console.log('faaaaaaaail-------------')
} else {
console.log('passssssssssssssssss-----------')
}
});
}
async function hostping(hosts) {
console.log('hosts-----------', hosts)
await hosts.forEach(async function(host) {
await ping.sys.probe(host, async function(isAlive) {
var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
console.log(msg);
if (isAlive == 'false') {
hoststatus = 1
}
});
});
return hoststatus;
}
test()