0

Okay, I have searched far and wide. I can't figure out why my array.push gives me [] and not (#) {...}, {...}, {...}, etc. Here is my relevant code:

let newArray = [];

const fetchAll = async (urls) => {
    const res = await Promise.all(urls.map(u => fetch(u)))
    const jsons = await Promise.all(res.map(r => r.json()))

    for (let i = 0; i < jsons.length; i++) {
        for (let j = 0; j < 2; j++) {
            newArray.push({
                'img': jsons[i].hits[j].previewURL
            });
        }
    }
}

Like I said, I specifically want the array to output like (#) {...}, {...}, {...} etc. Right now I'm just getting [ ]. With the array.

For reference: I want my array to look like the bottom console.log. The top is what I'm getting.Screenshot of console.log

UnclePete
  • 25
  • 5
  • 1
    Both of these are relevant: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) + [Is Chrome’s JavaScript console lazy about evaluating objects?](https://stackoverflow.com/q/4057440) – VLAZ Mar 29 '22 at 11:37
  • 1
    Also note that your code need to check for HTTP success before calling `json` but doesn't (my blog post on this `fetch` API footgun [here](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)), and there's no reason for two calls to `Promise.all`, just do a chain: ```const objects = await Promise.all(urls.map(url => fetch(url).then(resp => { if (!resp.ok) { throw new Error(`HTTP error ${resp.status}`); } return resp.json(); })));``` (I didn't call it `jsons` because it's an array of objects, not JSON.) – T.J. Crowder Mar 29 '22 at 11:41
  • Hey thanks @VLAZ The Chrome one was interesting. I opened it in Firefox, and sure enough. The array was exactly the same. Maybe it's just an issue with my controller... – UnclePete Mar 29 '22 at 11:44
  • You just need to wait for a while before reading your array. To prove to yourself that it is a timing issue try `setTimeout(()=>console.log(newArray), 1000) /* wait 1 second */`. To get the result as soon as `fetchAll` completes do : `fetchAll().then(()=>console.log(newArray))`. Learn how to use promises – slebetman Mar 29 '22 at 11:45
  • @UnclePete no, it's the same behaviour in both browsers. Objects are always dynamically evaluated in the console. You're printing an array which is empty first (hence the `[]` but it later gets populated. When you expand it, you see the contents which *weren't there* at the time of printing it. – VLAZ Mar 29 '22 at 11:46
  • @slebetman AHHHH... Gosh dang it was driving me up the wall. Thank you. – UnclePete Mar 29 '22 at 11:52

0 Answers0