0

I'm currently writing a discord bot on node.js that will get fed a link, and store the JSON data in that link to its own file, everything is working so far, however the "getValues" function continues to return as undefined, (even though the return of the function when you use console.log inside of it gives a numeric value.) the issue seems to be the totals variable, but regardless of where I place it, the function continues to return as undefined.

Here is the total code:

module.exports = {
    name: 'order',
    description: "Order things!",
    execute(message, args, listOfOrders) {
        const fs = require('fs');

        const fetch = require('node-fetch');

        let orderNum = listOfOrders[0].order++;

 
        // API stuff (This is the part that destroyed my progress.)

        let url = args[1];

        let settings = { method: "Get" };

        function getValues(request) {
            fetch(url, settings)
                .then(res => res.json())
                .then((json) => {

                    let processJson = [];

                    processJson.push(json);

                    jsonInfo = JSON.stringify(processJson[0].totals, null, 2);

                    let totals = JSON.parse(jsonInfo);


                    if (request == "sell") {
                        return totals.sell

                    } else if (request == "volume") {

                        return totals.volume
                        
                    }
                   
                });

        }

    // After that everything works as intended.

        listOfOrders.push({
            link: args[1],                             // Order link

            amount: args[0],                            // How many of these orders do you want do you want?
            volume: getValues("volume"),                // Get the total volume
            sellValue: getValues("sell"),               // Get the total sell value

            author: message.author.id,                  // Id of who made the order
            authorName: message.author.username,        // Username of who made the order

            number: orderNum,                           // Unqique order number idenifier
            inprogressby: "",                           // Who is doing it
            progressAuthor: "",                         // Id of the person hauling it

            delivered: false,                           // has it been delivered?
            complete: false                             // have both parties agreed to close it?

        });

        listOfOrders = JSON.stringify(listOfOrders, null, 2);


        fs.writeFile('data/orderlist.json', listOfOrders, finished);

        function finished(err) {
            console.log("Written to file!");
        }

        message.channel.send("Haul order: #" + orderNum + " has been issued for " + args[1] + " " + args[0] + " by: " + message.author.username + "\n" + "You can see all orders by !show.orders");

    }

}

and if I move the variables around like so:

 let url = args[1];

        let settings = { method: "Get" };

        let totals = "";

        function getValues(request) {
            fetch(url, settings)
                .then(res => res.json())
                .then((json) => {

                    let processJson = [];

                    processJson.push(json);

                    jsonInfo = JSON.stringify(processJson[0].totals, null, 2);

                    totals = JSON.parse(jsonInfo);

                   
                });

                if (request == "sell") {
                    return totals.sell

                } else if (request == "volume") {

                    return totals.volume
                    
                }

        }

It still returns as undefined. I am probably missing something very basic and simple I should know already but alas, I arrive here in my hour of need. Thank you for reading.

Tango
  • 13
  • 2
  • you have to make `getValues` function asynchronous. the reason you are getting `undefined ` is because function is getting executed before `fetch` has retrieved the value. learn more about here https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous – Atik Hashmee Mar 06 '21 at 06:17
  • In the first example, your `return` inside of `getValues` returns to the caller of the immediate function that the `return` appears in, which is the `(json) => {` callback for `.then()`. This means that your `getValues()` isn't returning anything, and is returning `undefined`. In your second attempt, you're trying to set `totals` and then return. However, `totals` is only being set _after_ your if-statement is being evaluated, and your function has returned since the callback `(json) => {` instead of `.then()` occurs some time _after_ you have performed your `fetch()` - ie: it's asynchronous – Nick Parsons Mar 06 '21 at 06:20

0 Answers0