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

109
Visualizações
Is it safe to update counter from inside one of Promise.all promises in Node.js?

Node.js uses threads from worker pool to perform I/O operations. If I need to count the number of characters in many files concurrently (using Promise.all), is it safe to update the totalNumberOfChars variable which is common to all promisifed file read operations? Because a separate thread may be used for each read operation can totalNumberOfChars be incorrect?

This is the code:

const fs = require("fs");
const util = require("util");
const readFileAsync = util.promisify(fs.readFile);

/**
 * 
 * @param {Array} pathsToFiles - array of paths to files
 */
const main = async (pathsToFiles) => {
  let totalNumberOfChars = 0;
  await Promise.all(
    pathsToFiles.map(async (path) => {
      const chars = await readFileAsync(path);
      totalNumberOfChars += chars.length;
    })
  );
  console.log("totalNumberOfChars", totalNumberOfChars);
};

main(['/home/a.txt', '/home/b.txt'])
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is safe, because what's inside this function:

pathsToFiles.map(async (path) => {
    const chars = await readFileAsync(path);
    totalNumberOfChars += chars.length;
})

is executed synchronously, meaning that your file is read synchronously (again, inside that callback!) and you're adding to counter synchronously as well. So after the "main" function's execution you'll receive the right answer.

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