-3

Basically, what happens is every time I refresh my page, there's a slight chance that my for loop goes from 1 to 0. I don't know why this happens, but it's affecting the way my images layer over each other.

I tried to use a foreach loop, but it still gave me the same results.

Here's the code to the for loop:

for (let index = 0; index < Img.length; index++) {
  const element = Img[index];
  fs.readFile(__dirname + '/assets/textures' + element, function(err, data) {
    console.log("Index: " + index);
  });
};

And the array is pretty straight forward.

let Img = ["/red.png", "/face.png"];

I'm doing this all on server. NodeJS

Aleksandar
  • 844
  • 1
  • 8
  • 18
Rokborr
  • 33
  • 8
  • 7
    It’s more likely you’ve misunderstand the async nature of `readFile`. – Dave Newton May 01 '23 at 22:57
  • 1
    What's your question? Do you want to know, why this happens? Do you want to achieve a specific behavior? – jabaa May 01 '23 at 22:59
  • I don’t want it to randomly go from 1 to 0. I am layering images and it messes up the layers. – Rokborr May 01 '23 at 23:01
  • My solution is: Use the promise version of `fs.readFile`. Replace the loop with `Img.map` and map each image to a promise. Await all promises with `Pormise.all`. I guess, your actual callback isn't a simple `console.log`. There should be hundreds of duplicates, but it's difficult to search for them. – jabaa May 01 '23 at 23:07
  • 1
    Does this answer your question? [Asynchronous Process inside a javascript for loop](https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop#11488129) I guess you want _"**Run asynchronous operations in parallel and use Promise.all() to collect results in order**"_ – jabaa May 01 '23 at 23:12

1 Answers1

-1

Try this

let Img = ["/red.png", "/face.png"];

async function prepareImages() {
  for (let index = 0; index < Img.length; index++) {
    const element = Img[index];
    await loadImage(element)
  };
}

function loadImage(element) {
  return new Promise((resolve, reject) => {
    fs.readFile(`${__dirname}/assets/textures${element}`, function(err, data) {
      console.log("dir ", `${__dirname}/assets/textures${element}`);
      if(err) {
        reject("Error: ", err)
      }
      
      resolve(data);
    });
  })
}
iftikharyk
  • 870
  • 5
  • 10