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.