Home  >  Q&A  >  body text

for loop randomly goes from 1 to 0

Basically, every time the page is refreshed, the for loop may change from 1 to 0. I don't know why this happens, but it affects the way my images are layered on top of each other.

I tried using a foreach loop but it still gave me the same result.

This is the code for 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);
  });
};

Arrays are very simple.

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

I'm doing this all on the server. NodeJS

P粉731977554P粉731977554194 days ago487

reply all(1)I'll reply

  • P粉099985373

    P粉0999853732024-04-07 12:46:26

    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);
        });
      })
    }

    reply
    0
  • Cancelreply