Loop in my code is not working

Fetch is working fine, but once i do console.log each results, nothing happens.

Is it because fetch is still running in background? Is there any better solution?

let timeStart;
let timeEnd;
let cardsData = [];
fetch('https://randomuser.me/api?results=10')
    .then((response) => {
        timeStart = new Date().getTime(); 
        return response.json();
    })
    .then((data) => {
        cardsData.push(...data.results);
        timeEnd = new Date().getTime();
        console.log((timeEnd - timeStart) / 1000 + " Seconds");
    });    


cardsData.forEach((element, i) => {
    const name = element.name.first + " " + element.name.last;
    console.log(name);
});


// Foreach loop in cardsData is not working

Hello @Codernim,

The javascript’s execution is fast. The fetch is a promise. Codes in then method only execute when the promise is fulfill. But the code under it got executed if the promise is fulfilled or not.
For example:
In a class students are writing stories. And the teacher tell them to come to her when she call. So students are listening to her but still writing stories before the teacher call them. And if teacher call them they go to her.

Hope This Help

2 Likes

You can access cardsData inside the second then. That’s the point data is available after the fetch and conversion to json are done.

So only solution available is to loop inside .then() right?

You can wrap the loop/logging code inside a function that you call inside the async code after the push. Or you can just pass the data to the function.

Example:

fetch("https://randomuser.me/api?results=10")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    logUsers(data.results);
  });

function logUsers(users) {
  users.forEach((element, i) => {
    const name = element.name.first + " " + element.name.last;
    console.log(name);
  });
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.