I can't find way to fix this bug, I tried so many things but it's not working, IDK what am I doing wrong.
I have a function which should return array of objects with questions, but it returns array with length 0 so I can't iterate over it. I am using axios to make api call.
I am also bubble sorting the difficulty property inside the array object, so it starts from easy and goes to hard.
let getQuestions = () => {
let questions = [];
axios
.get('https://opentdb.com/api.php?amount=10')
.then((res) => {
for (let i = 1; i < res.data.results.length; i++) {
for (let j = 0; j < res.data.results.length - 1; j++) {
if (
res.data.results[j].difficulty.charCodeAt(3) <
res.data.results[j + 1].difficulty.charCodeAt(3)
) {
const temp = res.data.results[j];
res.data.results[j] = res.data.results[j + 1];
res.data.results[j + 1] = temp;
}
}
}
for (const i in res.data.results) questions.push(res.data.results[i]);
})
.catch((err) => console.error(err));
return questions;
};
console.log(getQuestions());
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>