Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!