Search code examples
javascriptjsonfetch

Json fetch returning elements in random order


I am having trouble with a fetch request, the thing is that for some reason it's returning the elements in random order. The function is the following:

function create_post_div(element, isLogged, currentUser, isProfile) {
      console.log(element.id);
    
      fetch(`likes/${element.id}`)
        .then((response) => response.json())
        .then((like_element) => {
          console.log(like_element.user_liked, element.id);
      });
 }

For simplicity's sake I didn't put the whole function but the error can be detected with the console log. The first console log should return the element.id which are integers and the second the like_element.user_liked which is a boolean and the same element.id.

The create_post_div function has to run for each of the elements received from another function (let's say a list [1, 2, 3]). When I run the function the first console.log returns the numbers in the correct order, but the console.log inside the fetch return them randomly. Other thing that I noted is that instead of the console be something like:

1
true, 1
2
false, 2
3
true, 3

It logs like this:

1
2
3
false, 2
true, 3
true, 1

It will first log all of the id's and after log the likes with the ids. Again, the id's in the first log always in order and the second log always unordered.


Solution

  • When you use fetch you create a Promise, an operation that will take an undefined amount of time to complete. And Javascript doesn't wait for the promise to be completed, it keeps running doing all the other stuff that you have coded.

    Once the fetch operation is completed the code that you put inside the .then is executed, that is why it's called asynchronous code, because it's exectuted after an undefined amount of time.

    Rather than fighting this and trying to force the code to run syncronously with async / await like suggested I would reccomend rewiring your brain to understand and embrace this pattern. Unless it's absolutely necessary by design but it should be a very rare situation.