0

I'm new to javascript, playing with code to get some data from web service , I've used fetch to grab the data , having issues with the result data

 var tt = {ttpart:"Fiat", ttdesc:"500", ttum:"white"};
 
 var Orders = new Array();
 
 Orders.push(tt);
 
 fetch(url)
 .then(res => res.json())
 .then((data) => { 
    for ( tt of data.tt1) {
        Orders.push(tt);
        const listItem = document.createElement("h1");
    } 
 })
 .catch(err => { throw err });
 
 console.log(Orders);
 
 Orders.forEach((element) => {
     console.log(element);
 });
 
 console.log('test2');

everything works perfectly, except the last forEach loop displays only the first element. (the one pushed before fetch) If I remove that first push then there is nothing in forEach

yet, the 'console.log(Orders); shows me 30 objects in the array...(picture 1) how is that possible?

(also, if I try to display any object but first , i.e console.log(Orders[3]) I see 'undefined' in the log - picture 2)

picture2

picture1

question was closed as duplicate of the JS asynchronicity issue , I dont think thats the issue in my case as both 'console.log' entries are outside of fetch function, still first one shows 34 records but for each only shows one record...

  • 1
    JS sidenote: don't use `new Array()`, just use the array primitive, `const orders = [];`. Also don't use `var`, use `let` or `const` (depending on whether you need to be able to reassign the variable or note) and mark your variables. Don't have a `for (tt of ...)`, make that a `for(let tt of ...)` so it doesn't overwrite your global. Or if it _should_ overwrite it, then your global is unnecessary. And then of course on a "if you ever want others to read your code" note: remember to follow the JS naming conventions. Classes use UpperCamelCase, variables and functions use lowerCamelCase. – Mike 'Pomax' Kamermans Aug 08 '23 at 16:20
  • I've finally fixed that with moving fetch to separate async function and using await statement, still not sure why code above returns objects in first console.log but not in the second one... – Andrzej Litwinski Aug 09 '23 at 11:59

0 Answers0