我嘗試通過在函式內的節點 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);
}
uj5u.com熱心網友回復:
這是因為它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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/473812.html
上一篇:如何通過消除回圈來優化我的代碼?
