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

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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