Skip to content Skip to sidebar Skip to footer

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(ele

Solution 1:

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.

Solution 2:

You're just dealing with the beautiful of asynchronous operations.

See the last example on the TutorialsPoint NodeJS Course. This code:

const fs = require("fs");

fs.readFile("input.txt",
    (err, data) => err ? console.log(err.stack) : console.log(data.toString())
);
console.log("Program Ended");

outputs:

Program Ended
Some text.

In your case, you:

  1. Call create_post_div
    1. Logs the id
    2. Starts fetching
  2. Call create_post_div again
    1. Logs the id again
    2. Starts fetching again
  3. Call create_post_div again
    1. Logs the id again
    2. Starts fetching again

Then, for each fetched data (which is a random operation, as you can see...), logs it as the data is received. But, if there's no data received, your code doesn't log it. It just does so as when there is data. When you call fetch().then, the then method comes from a Promise. And JavaScript Promises promises to return / do something in the future, but not right now.

If you want more explanation, I will leave you with a link to a similar question in the comments.

Solution 3:

The fetch is asynchronous so console.log in the callback .then() could be in any order as you observed.

Most of the time this is fine. It should be another part of your code should be changed to adopt this async pattern.

However, if you want to force it running in a synchronous order, you can run it with a reduce.

Here is an example

const elements = [1, 2, 3];

functionsleep(ms) {
  returnnewPromise(resolve =>setTimeout(resolve, ms));
}

// this prints 3,2,1awaitPromise.all(
    elements.map(async (i) => {
      awaitsleep(10 - i);
      console.log(i);
    })
);

// and this prints 1,2,3await elements.reduce(async (prev, i) => {
    await prev;
    awaitsleep(10 - i);
    console.log(i);
}, undefined);

Post a Comment for "Json Fetch Returning Elements In Random Order"