Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Async/await logic in Javascript

I have a code that helps me rename multiple files with a data. In the data (rarityList) there is a name and a value for each file I have. For the sake of the post I just replaced the values with a dummy but you can imagine there is 500 of them.

It works and does the job but in a way that I did not intend. In the terminal it first prints 0(total) then copies all files and then renames it. But I was expecting to see something like Copying is done! and Renaming is done! and finally total number at the end of the terminal. Could you explain to me what I am missing here?

const fs = require("fs");
const path = "C:\\Users\\shepard\\Desktop\\Head";
const newPath = "C:\\Users\\shepard\\Desktop\\NewHead";
let files = fs.readdirSync(path);
const rarityList = [{name: "a", value: 3},{name: "b", value: 2}];
let total = 0;

const copy = async (_e) => {
    fs.copyFile(path + "\\" + _e, newPath + "\\" + _e, err => {if (err) {console.log(err)}});
  };

const rename = async (_e, _index) => {
    let t = _e.replace(".png", "#" + rarityList[_index].value + ".png")
    fs.rename(newPath + "\\" + _e, newPath + "\\" + t, err => {if (err) {console.log(err)}});
  };

files.forEach(async (e) => {
    await copy(e);
    console.log("Copying is done!");

    rarityList.forEach(async (element, index) => {
      if (element.name == e.slice(0,-4)) {
          await rename(e,index);
          console.log("Renaming is done! for " + e + " with the rarity weight of " + rarityList[index].value);
          total += rarityList[index].value;
      };
    });
});

console.log(total);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Possibly not the best answer, but a solution:

const fs = require("fs");
const path = "C:\\Users\\shepard\\Desktop\\Head";
const newPath = "C:\\Users\\shepard\\Desktop\\NewHead";
let files = fs.readdirSync(path);
const rarityList = [
  { name: "a", value: 3 },
  { name: "b", value: 2 },
];
let total = 0;

const copy = async (_e) => {
  fs.copyFile(path + "\\" + _e, newPath + "\\" + _e, (err) => {
    if (err) {
      console.log(err);
    }
  });
};

const rename = async (_e, _index) => {
  let t = _e.replace(".png", "#" + rarityList[_index].value + ".png");
  fs.rename(newPath + "\\" + _e, newPath + "\\" + t, (err) => {
    if (err) {
      console.log(err);
    }
  });
};

const renameFiles = async () => {
  for (let e of files) {
    await copy(e);
    let index = 0;
    for (let element of rarityList) {
      if (element.name == e.slice(0, -4)) {
        await rename(e, index);
        console.log(
          "Renaming is done! for " +
            e +
            " with the rarity weight of " +
            rarityList[index].value
        );
        total += rarityList[index].value;
      }
      index += 1;
    }
  }
  console.log('in async func', total);
};

renameFiles();
console.log('out of async function', total);

The trick is that the async function is not waited for, so total isn't updated at the "top level". You can do a "top level" await like this:

const fs = require("fs");
const path = "C:\\Users\\shepard\\Desktop\\Head";
const newPath = "C:\\Users\\shepard\\Desktop\\NewHead";
let files = fs.readdirSync(path);
const rarityList = [
  { name: "a", value: 3 },
  { name: "b", value: 2 },
];
let total = 0;

const copy = async (_e) => {
  fs.copyFile(path + "\\" + _e, newPath + "\\" + _e, (err) => {
    if (err) {
      console.log(err);
    }
  });
};

const rename = async (_e, _index) => {
  let t = _e.replace(".png", "#" + rarityList[_index].value + ".png");
  fs.rename(newPath + "\\" + _e, newPath + "\\" + t, (err) => {
    if (err) {
      console.log(err);
    }
  });
};

const renameFiles = async () => {
  for (let e of files) {
    await copy(e);
    let index = 0;
    for (let element of rarityList) {
      if (element.name == e.slice(0, -4)) {
        await rename(e, index);
        console.log(
          "Renaming is done! for " +
            e +
            " with the rarity weight of " +
            rarityList[index].value
        );
        total += rarityList[index].value;
      }
      index += 1;
    }
  }
  console.log("in function", total);
};

(async function() {
  await renameFiles()
  console.log(total)
}());
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda