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

226
Views
No puedo entender por qué hay esta salida con 'foreach' en node.js

Soy nuevo en node.js y estoy luchando con este problema. No entiendo por qué mi salida es

 ciao data data

y no

 data data ciao

este es mi codigo

 fs.readdir("sender", (err, files) => { if (err) { throw err; } const path = __dirname + "/sender/"; let rawdata = fs.readFileSync(path + "data.json"); var data = JSON.parse(rawdata); files.forEach((file) => { fs.stat(path + file, (err, stats) => { if (err) { throw err; } if (data[file]["size"] != stats.size) data[file]["size"] = stats.size; if (data[file]["time"] != stats.mtime.toISOString()) data[file]["time"] = stats.mtime.toISOString(); console.log("data"); }); }); console.log("ciao"); });

He leído que foreach no es asíncrono, por lo que realmente no entiendo por qué se invierte la salida.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

forEach no es asíncrono. Pero la operación que está realizando en la devolución de llamada forEach , fs.stat , es asíncrona.

Entonces, lo que está haciendo su código es comenzar una serie de operaciones fs.stat (parece que dos), luego registrar ciao , luego, cuando se completa cada una de esas operaciones fs.stat , está registrando data .

En su lugar, podría usar la API del sistema de archivos basada en promesas y usar async / await ; ver comentarios:

 const {readdir, readFile, stat} from "fs/promises"; // This version of `readdir` returns a promise fs.readdir("sender") .then(async files => { // Use an `async` function as the fulfillment callback const path = __dirname + "/sender/"; // Await the promise from `readFile` (no need to use `readFileSync`) const rawdata = await readFile(path + "data.json"); const data = JSON.parse(rawdata); // Wait for all operations to complete (they run in parallel) await Promise.all(files.map(async file => { // Get the stats (again, awaiting the promise) const stats = await stat(path + file); // Update the entry for the file. const entry = data[file]; if (entry.size != stats.size) { // (There's no point to this comparison, just do the assignment) entry.size = stats.size; } if (entry.time != stats.mtime.toISOString()) { // (Again) entry.time = stats.mtime.toISOString(); } console.log("data"); })); // Since this is after the `await` on the promise from `Promise.all`, it doesn't run until all // of the promises `Promise.all` was waiting on have been fulfilled console.log("ciao"); }) .catch(error => { // ...log/handle error... });
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!