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)
})
})
})
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))
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();