0

So I'm relatively new to Javascript but I'm making a memory game in html using javascript. I'm using an api to fetch 18 images and I put them all in an array twice, so I can shuffle the list and assign the images to my 36 cards.

var images_list = [];
var response = fetch('https://dog.ceo/api/breeds/image/random')
  .then(response => response.json())
  .then(data => {
    images_list.push(data.message);
    images_list.push(data.message);
  });
shuffle(images_list);

After this I get all the 36 memory-cards and assign them all one of the pictures.

var backViewList = document.getElementsByClassName("back-view");

        for (var i=0; i < backViewList.length; i++) {

            console.log(images_list);


            var img = backViewList[i].querySelector("img");
            img.src = images_list[i]; 
        }

the console.log(images_list); shows me an array with 36 url's to images, as you would expect. But when I console.log(images_list[0]; or any other index, this returns undefined. I can't seem to figure out why he does this. Can anyone explain this to me?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
PiiMY
  • 53
  • 1
  • 6
  • `fetch()` is an **asynchronous** mechanism. – Pointy Jun 09 '23 at 14:30
  • Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton Jun 09 '23 at 14:31
  • but the ```console.log(images_list)``` shows me a perfect array with the data in it. – PiiMY Jun 09 '23 at 14:31
  • 1
    @PiiMY The first snippet accesses `images_list` before the `fetch` has completed. – Dave Newton Jun 09 '23 at 14:32
  • @PiiMY `console.log` sometimes performs lazy lookups of object references. `console.log(images_list.length)` will show `0`; `console.log(images_list.slice())` will show the current copy of the array. See [Is Chrome’s JavaScript console lazy about evaluating objects?](/q/4057440/4642212). – Sebastian Simon Jun 09 '23 at 14:33
  • but how do i fix this? Because when I use await the rest of my game completely crashes. – PiiMY Jun 09 '23 at 14:34
  • @PiiMY How are you trying to use `await`? See [top-level `await`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/await#top_level_await). – Sebastian Simon Jun 09 '23 at 14:36
  • 1
    @PiiMY: "How do i fix this" could potentially involve significant logical changes, we don't really know the overall structure of your code. The underlying fact however is that you can't use data fetched from the server before that data has been received by the client. Whatever operation is to be performed on the data fetched from the server would need to be performed *after* it's received. In the code shown that would be in the `.then()` callback. – David Jun 09 '23 at 14:36

0 Answers0