无法使用循环节点 js 将数据插入变量
failed to insert data into variable with looping node js
我尝试在函数内部的节点 js 上循环将数据插入变量,但是当我尝试将数据推送到电报机器人时,变量为空,如何正确地将数据插入变量。
错误:
代码:
async function brokeServer(listServer) {
let nothing = '';
for (const newServer of listServer) {
ping.sys.probe(newServer.srv_ip, async function(isAlive){
let msg = isAlive ? 'host ' + newServer.srv_ip + ' is alive' : 'host ' + newServer.srv_ip + ' is dead';
//console.log(msg);
let myspace = '\n';
nothing+=myspace;
nothing+=msg;
});
}
MeikelBot.sendMessage(-721865824, nothing);
}
这是因为 ping.sys.probe
仍然是异步的,尚未正确处理。你需要把它变成 Promise
然后它应该与 async
函数和 for
循环一起工作。
示例(请注意这是未经测试的):
function ProbePromise(server_ip) {
return new Promise((resolve) => {
ping.sys.probe(server_ip, async function(isAlive){
resolve(isAlive)
})
})
}
async function brokeServer(listServer) {
let nothing = '';
for (const newServer of listServer) {
// use the promise version of Probe
let isAlive = await ProbePromise(newServer.srv_ip)
let msg = isAlive ? 'host ' + newServer.srv_ip + ' is alive' : 'host ' + newServer.srv_ip + ' is dead';
//console.log(msg);
let myspace = '\n';
nothing+=myspace;
nothing+=msg;
}
MeikelBot.sendMessage(-721865824, nothing);
}
我尝试在函数内部的节点 js 上循环将数据插入变量,但是当我尝试将数据推送到电报机器人时,变量为空,如何正确地将数据插入变量。
错误:
代码:
async function brokeServer(listServer) {
let nothing = '';
for (const newServer of listServer) {
ping.sys.probe(newServer.srv_ip, async function(isAlive){
let msg = isAlive ? 'host ' + newServer.srv_ip + ' is alive' : 'host ' + newServer.srv_ip + ' is dead';
//console.log(msg);
let myspace = '\n';
nothing+=myspace;
nothing+=msg;
});
}
MeikelBot.sendMessage(-721865824, nothing);
}
这是因为 ping.sys.probe
仍然是异步的,尚未正确处理。你需要把它变成 Promise
然后它应该与 async
函数和 for
循环一起工作。
示例(请注意这是未经测试的):
function ProbePromise(server_ip) {
return new Promise((resolve) => {
ping.sys.probe(server_ip, async function(isAlive){
resolve(isAlive)
})
})
}
async function brokeServer(listServer) {
let nothing = '';
for (const newServer of listServer) {
// use the promise version of Probe
let isAlive = await ProbePromise(newServer.srv_ip)
let msg = isAlive ? 'host ' + newServer.srv_ip + ' is alive' : 'host ' + newServer.srv_ip + ' is dead';
//console.log(msg);
let myspace = '\n';
nothing+=myspace;
nothing+=msg;
}
MeikelBot.sendMessage(-721865824, nothing);
}