0
async function apiRequest(id) {
    let res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
    let finalRes = await res.json();
    return finalRes;
}

let array = [];

async function main() {
    for (let i = 1; i <= 5; i++) {
        let res = await apiRequest(i);
        array.push(res);
    }
}

console.log(array); // I can see the out put in the console

array.forEach((element) => {
    console.log(element); // but no out put is shown in the console
});

main();

Why can't I see output when I iterate through the array? When I print the array it shows the output and prints all elements. But in forEach block nothing is printed.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • where is main called? Where are you looping over the array? hint hint hint. You log out the result BEFORE you call a function that adds the items to the array. Now why does console show the result for first log, answer lazy load in console. – epascarello Aug 16 '22 at 21:20
  • you need to await main() – Nonik Aug 16 '22 at 21:29
  • Use `console.log(JSON.stringify(array, null, 2))` to get a print out of what's in `array` at the moment `console.log` is called. – Heretic Monkey Aug 16 '22 at 21:29
  • It might be easier [to build an array of promises](https://pastebin.com/uGhWTufq), and then return and log the result of calling `Promise.all(promises)`. – Andy Aug 16 '22 at 21:49

0 Answers0