我是 Node.js 新手,目前正在学习 Promise 和等待/异步。我尝试了下面的代码,但不知道如何让代码等待函数
hostping
完成。我也尝试过承诺,但等不及了。
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()
要做你想做的事,你应该使用 ping 的 Promise 包装器以及 for..of 因为 forEach 不能与异步一起工作。
下面是对代码的修改,以使流程按您的预期工作:
const ping = require('ping');
const hosts = ['google.com', 'yahoo.com'];
async function test()
{
const status = await hostping(hosts);
if (status) {
console.log('All hosts are alive');
} else {
console.log('Some/all hosts are dead');
}
}
function hostping(hosts) {
let status = true;
return new Promise(async function(resolve, reject) {
for (const host of hosts) {
const res = await ping.promise.probe(host);
var msg = `host ${host} is ${res.alive ? 'alive' : 'dead'}`;
console.log(msg);
if (!res.alive) { status = false; }
}
console.log('all host checks are done, resolving status');
resolve(status);
});
}
test()
如果您有兴趣了解有关异步的更多信息,这些都是值得阅读的好文章: https://www.coreycleary.me/why-does-async-await-in-a-foreach-not-actually-await/
https://itnext.io/javascript-promises-and-async-await-as-fast-as-possible-d7c8c8ff0abc
这应该符合您的要求,我们使用 for .. of 循环按顺序迭代主机。
ping 库还有一个 Promise 包装器,允许您跳过使用回调。
您也可以使用 Promise.all 一次执行所有 ping 和探测,但我不认为这是您想要做的。
如果您想一次执行所有 ping,我已经包含了一个使用 Promise.all 的 hostpingVer2。
const ping = require('ping');
const hosts = ['google.com', 'amazon.com', 'itdoesntexist'];
async function test() {
console.log('hosts: ', hosts)
const results = await hostping(hosts);
console.log('ping results: ', results);
}
async function hostping(hosts) {
const results = [];
for(let host of hosts) {
let probeResult = await ping.promise.probe(host);
results.push( { host, hoststatus: probeResult.alive ? 0: 1, alive: probeResult.alive } );
}
return results;
}
async function hostpingVer2(hosts) {
const probeResults = await Promise.all(hosts.map(host => ping.promise.probe(host)));
return probeResults.map(probeResult => {
return { host: probeResult.host, hoststatus: probeResult.alive ? 0: 1, alive: probeResult.alive }
});
}
test();
您在
forEach
中使用await,这不应该工作,因为forEach不支持承诺。考虑将其更改为 for..of
或 promise.all
。
此外,您的探测函数是回调样式,不返回承诺。你需要用一个承诺来等待它。
function probe(host) {
return new Promise((resolve, reject) => {
ping.sys.probe(host, function (isAlive) {
const msg = isAlive ? `host ${host} is alive` : `host ${host} is dead`;
console.log(msg);
resolve(isAlive);
});
});
}
async function hostping(hosts) {
console.log("hosts-----------", hosts);
for(const host of hosts) {
// eslint-disable-next-line no-loop-func
// eslint-disable-next-line no-await-in-loop
const isAlive = await probe(host);
if (isAlive === "false") {
hoststatus = 1;
}
}
return hoststatus;
}