JavaScript is synchronous, thus each line of code will be executed right after one another.
If we annotate your code with line numbers like below
1. let splatshArtData = [];
2. splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => {
3. splatshArtData.push(splatshArtUrl);
});
4. console.log(splatshArtData);
you are assuming that it will run in the order of 1, 2, 3, 4, while in reality it will run in the order of 1, 2, 4, 3. Why is that? Because JavaScript is synchronous, and the function at line 2 is asynchronous, meaning that you'll have to await that before you can continue. If you don't the splatshArtData
variable will be an empty array since the data hasn't been fetched yet.
If you want to return the fetched data and use it in another function, you shouldn't mix it will callbacks as suggested in another answer, but instead chain the promise and use the resolved value from the function that fetches the data.
function getSplatshArt() {
let splatshArtData = [];
//Return a promise
return splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => {
console.log(splatshArtData); //this will log out the data
splatshArtData.push(splatshArtUrl);
return splatshArtData; //this will be the resolved value from the promise
});
}
//Call the function and access the resolved data in the .then() block
getSplatshArt()
.then(data => {
console.log(data); //this is the data returned from the getSplatshArt function
});
Looking at your code, I get the impression that you're looping over an array of ID's, and if you want to fetch multiple values at once, this wont work since you have to handle multiple promises. But that is another question and I think you should do some more research of your own before asking about that.