-1

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>
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • The HTTP request is asynchronous. Your `console.log` happens before the `then` callback code is executed. At that moment the length is still 0. When in the console, you click and expand the array, you'll find indeed contents, since by the time you expand, the array got populated. But it was not there when the `console.log` executed. – trincot Dec 29 '20 at 17:07

1 Answers1

0

If you are using the returned value then the issue is axios takes time to fetch the data from the API, but in the meantime control moves forward and executes the return statement at which point the value of questions is []. I would suggest using async await syntax instead of then() callback. You simply await for the response from the API and when the response is received the only you return the response from the function.

Hardik3296
  • 336
  • 2
  • 14