简体   繁体   中英

JavaScript not getting function returns in Node.js

I have made an IRC bot for purely learning purposes but I have a Minecraft server that I use an API to get the status back as JSON. Now I have made the code and it works but for some reason when I try and use a return on the function so I can get the content it seems to not work?

So I have the two functions below:

    function getservers(name) {
        if (name == "proxy") {
            var Request = unirest.get(proxy);

            Request.header('Accept', 'application/json').end(function (response) {
              main = response["raw_body"];
              data = JSON.parse(main);
              console.log(data["motd"]);
              return data.motd;
            });
        } else if (name == "creative") {
            var Request = unirest.get(creative);

            Request.header('Accept', 'application/json').end(function (response) {
              main = response["raw_body"];
              data = JSON.parse(main);
              return data;
            });
        } else if (name == "survival") {
            var Request = unirest.get(survival);

            Request.header('Accept', 'application/json').end(function (response) {
              main = response["raw_body"];
              data = JSON.parse(main);
              return data;
            });
        }
    }

    // Main logic:
    function parsemessage(msg, to) {
        // Execute files
        function pu(o,t,f){if(o)throw o;if(f)throw f;bot.say(to,t)}
        if (msg.substring(0,1) == pre) {
            // Get array
            msgs = msg.split(' ');

            console.log(msgs[0]);

            // Run Login
            if (msgs[0] == pre+"help") {
                bot.say(to, "Help & Commands can be found here: https://server.dannysmc.com/bots.html");
            } else if (msgs[0] == pre+"status") {
                // Get status of server, should return online/offline - player count for each server - motd

                server = getservers("proxy");
                console.log(server);

                /*var data = '';

                var Request = unirest.get('https://mcapi.us/server/status?ip=185.38.149.35&port=25578');

                Request.header('Accept', 'application/json').end(function (response) {
                  main = response["raw_body"];
                  data = JSON.parse(main);
                });


            } else if (msgs[0] == pre+"players") {
                // Should return the player list for each server



            } else if (msgs[0] == pre+"motd") {
                // Should return the message of the day.



            } else if (msgs[0] == pre+"ip") {
                bot.say(to, "ShinexusUK IP Address: shinexusuk.nitrous.it");        
            } else if (msgs[0] == pre+"rules") {

            }
        }
    }

The code in the getservers() function works, when I do the

console.log(data["motd"]);

It outputs my servers message of the day. But when I do return

data.motd 

(same as data["motd"]?) The code that calls the function is here

server = getservers("proxy");
console.log(server);

Please note this is a node.js code and it contains many files so i can't exactly paste it. So here is the link to the github repo with the whole node application: Here

When the function getservers is called, it makes an asynchronous request and return nothing. Then the callback is fired with the response of that request as parameter.

Note that the function getservers will end before the end callback of your request is called

(simplified version)

function getservers(name) {
    var Request = unirest.get(proxy);

    Request.header('Accept', 'application/json').end(function (response) {
        main = response["raw_body"];
        data = JSON.parse(main);
        console.log(data["motd"]);
        return data.motd;
    });

    // nothing returned here
}

What you need is a function callback that will be called after you got the response.

function getservers(name, callback) { // callback added
    var Request = unirest.get(proxy);

    Request.header('Accept', 'application/json').end(function (response) {
        main = response["raw_body"];
        data = JSON.parse(main);
        console.log(data["motd"]);
        callback(data.motd);    // fire the callback with the data as parameter
    });

    // nothing returned here
}

And then you can use your function like this :

getservers("proxy", function(server){

     console.log(server);

     ....
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM