Home > Mobile >  failed to insert data into variable with looping node js
failed to insert data into variable with looping node js

Time:05-14

i try to insert data into variable with looping on node js inside function, but when i try to push the data into telegram bot, the variable is empty, how to insert the data into the variable properly.

the error : enter image description here

the code :

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);
    
}

CodePudding user response:

Its because the ping.sys.probe is still asynchronous and not yet handled properly. You need to turn it to Promise then it should work with the async function & for loop.

Example (please note this is untested):

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);
}
  • Related