Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
How to use Promise to add up multiple value?

I want to read the three txt files, and add up the text results return from realFile(), below is my code used callback. How do we use Promise and .then() to add up all text?

fs.readFile('./a.txt', 'utf8', (err, data) => {
   if(err) console.log(err)
   fs.readFile('./b.txt', 'utf8', (err, newData) => {
     if(err) console.log(err)
     fs.readFile('./c.txt', 'utf8',(err, newestData) => {
       if (err) console.log(err)
       console.log(data+newData+newestData)
     })
   })
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use the fs.promises API to obtain promisified methods.

Then, just do a Promise.all:

const p1 = fs.promises.readFile('./a.txt', 'utf8')
const p2 = fs.promises.readFile('./b.txt', 'utf8')
const p3 = fs.promises.readFile('./c.txt', 'utf8')

Promise.all([p1, p2, p3])
  .then(([v1, v2, v3]) => console.log(v1 + v2 + v3))
  .catch(e => console.error(e))

You can also avoid repetition with arrays:

const files = ['./a.txt', './b.txt', './c.txt']

Promise.all(
  files.map(file => fs.promises.readFile(file, 'utf8'))
)
  .then(([v1, v2, v3]) => console.log(v1 + v2 + v3))
  .catch(e => console.error(e))

If you are really looking for something with multiple .then()s in it, you could do it this way (though it's not much better than your original callback thing):

fs.promises.readFile('./a.txt', 'utf8').then(v1 => 
  fs.promises.readFile('./b.txt', 'utf8').then(v2 => 
    fs.promises.readFile('./c.txt', 'utf8').then(v3 => 
      console.log(v1+v2+v3)
    )
  )
)
  .catch(e => console.error(e))
about 4 years ago · Juan Pablo Isaza Denunciar

0

Check the code snippet below I have added logic for both promises and async/await



    const fs = require('fs');
    const util = require("util");

    const readFile = util.promisify(fs.readFile);

    // return promise which can resolved later
    // data is array of promise in same order of 
    let data = Promise.all([
        readFile('file.txt', 'utf8'),
        readFile('file.txt', 'utf8'),
        readFile('file.txt', 'utf8')
    ])

    data.then(([data1, data2, data3]) => {
        console.log(data1, data2, data3)
    }).catch(error => console.log(error))

We can achieve this using async/await with even simple syntax



    const fetchData = async () => {
        const data1 = await readFile('file.txt', 'utf8');
        const data2 = await readFile('file.txt', 'utf8');
        const data3 = await readFile('file.txt', 'utf8');
        console.log(data1, data2, data3);
    }

    fetchData();

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda