im pretty new to node.js, or web development in general so i might have gotten this all wrong. Im trying to code a simple discord Bot that sends a message containing specific content from more than one api call. i've heard some stuff about async/await and how important it is, but i dont really understand how to implement it into my code.
module.exports = {
name: 'mastery',
description: 'displays the three highest mastery champs of a given user',
execute(message, args){
const https = require('https');
const apiKey = 'my api key';
const summonerDataURL = 'https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+args +'?api_key='+ apiKey;
var masteryData = [ ];
var summonerData;
var summonerID;
var firstChampion = [];
var secondChampion = [];
var thirdChampion = [];
//this is the first api call. it stores the encrypted summonerID which i need to access the second api call.
https.get(summonerDataURL, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(JSON.parse(data));
summonerData = JSON.parse(data);
console.log(summonerData.id);
summonerID = summonerData.id;
});
}).on("error", (err) => {
console.log("Error: "+ err.message);
});
const masteryDataURL = 'https://euw1.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/'+ summonerID +'?api_key='+ apiKey;
//this is the second api call.it needs to wait for the first call to finish and store the summonerID or else it will return nothing of value. it stores the actual content i need and also sends the message into the discord.
https.get(masteryDataURL, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
masteryData = JSON.parse(data);
firstChampion[0] = masteryData[0].championId;
firstChampion[1] = masteryData[0].championLevel;
firstChampion[2] = masteryData[0].championPoints;
console.log(firstChampion[0], ' ', firstChampion[1], ' ', firstChampion[2]);
secondChampion[0] = masteryData[1].championId;
secondChampion[1] = masteryData[1].championLevel;
secondChampion[2] = masteryData[1].championPoints;
console.log(secondChampion[0], ' ', secondChampion[1], ' ', secondChampion[2]);
thirdChampion[0] = masteryData[2].championId;
thirdChampion[1] = masteryData[2].championLevel;
thirdChampion[2] = masteryData[2].championPoints;
console.log(thirdChampion[0], ' ', thirdChampion[1], ' ', thirdChampion[2]);
message.channel.send(args+'s'+'championmasterypoints: \n'+
firstChampion[0] + ' ' +'lvl'+firstChampion[1]+' '+firstChampion[2]+'\n'
+secondChampion[0]+ ' '+ 'lvl'+secondChampion[1]+' '+secondChampion[2]+'\n'
+thirdChampion[0]+ ' '+ 'lvl'+thirdChampion[1]+' '+thirdChampion[2]
);
});
}).on("error", (err) => {
console.log("Error: "+ err.message);
});
}
};
coming from basic c++, i thought js would work its way down but it doesnt seem to work that way? or am i completely on the wrong path?