I want to get 10 calls, each call to this endpoint return me a single item so i used axios in a for loop.
In the axios call I push in the empty array the response.data, but for timing issues (I think) if I console.log(wordsArray) outside the for loop it consoles a "strange" apparently empty array that can be opened and it has objects inside, but they don't seem to be part of the array.
Also if I try to console.log(wordsArray[0]) outside the for loop I get undefined.
What's wrong with the code??
let wordsNumber = 10;
let wordsArray = [];
for(i = 0; i < wordsNumber; i++) {
axios.get('https://flynn.boolean.careers/exercises/api/random/word')
.then( res => {
wordsArray.push( res.data )
// If I log the wordsArray here, inside the for loop, I get what I need.
// But obviously I need this to be outside of the loop.
// console.log( wordsArray )
})
.catch( err => {
console.log( err );
});
}
// logs an apparently empty array that can be opened, it has 10 objects inside
console.log( wordsArray )
// is undefined
console.log( wordsArray[0] )
This is the HTML, just for showing you the axios CDN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="script.js" defer></script>
<title>Project</title>
</head>
<body>
</body>
</html>