Answer the question
In order to leave comments, you need to log in
How to work with promises in this example?
There is a code that counts the size of all files in the current folder:
'use strict';
const fs = require('mz/fs');
fs.readdir(__dirname)
.then(function(filesNames) {
return Promise.all(
filesNames.map(fileName => fs.stat(fileName))
)
})
.then(function(stats) {
return stats.filter(stat => stat.isFile())
})
.then(function(stats) {
return stats.reduce((sum, stat) => sum + stat.size, 0)
})
.then(console.log);
stat.isFile()
we need to perform various manipulations with the contents of the file? Those. needs to be executed fs.readFile()
, and we have already lost the file name. Answer the question
In order to leave comments, you need to log in
Decision:
'use strict';
const fs = require('mz/fs');
fs.readdir(__dirname)
.then(filesNames => Promise.all(
filesNames.map(fileName => {
return fs.stat(fileName).then(stat => {
return {name: fileName, stat: stat};
});
})
)
)
.then(stats => stats.filter(
statsObj => statsObj.stat.isFile()
))
.then(stats => stats.reduce(
(sum, statsObj) => {
console.log(`${statsObj.name}: ${statsObj.stat.size}`);
return sum + statsObj.stat.size;
}, 0
))
.then(console.log)
.catch(error => console.log(error));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question