E
E
Emptyform2016-07-20 10:40:20
JavaScript
Emptyform, 2016-07-20 10:40:20

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

But what if after checking 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.
How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Emptyform, 2016-07-20
@Emptyform

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

V
Vitaly, 2016-07-20
@vshvydky

Emptyform Have you ever read about promises?
You pass in then through resolve What you need, in reject what you need to send in catch
in your case, the result is passed to resolve filesNames.map(fileName => fs.stat(fileName))
Refer to the JS documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question