Promises.all () in an array of objects with the "promised" property

Edit: within a few hours of requesting this question, I learned enough to understand that this question is the perfect example for blatant abuse of promises:

I am trying to convert a workflow to using promises because it was a terrible rat nest of callbacks, and I walked well until I got to a specific function. I am trying to use the promised version of readFile () to retrieve the contents of a series of files, but I also need to hold the file name for each file so that it can be added to an object that will eventually parse the contents of the file in the next step / function. This file name is only available when I repeat the list of file names (and create promises to return the contents of the file). Now I have this that will not work:

    // Accepts a sequence of filenames and returns a sequence of objects containing article contents and their filenames
    function getAllFiles(filenames) {
      var files = []; // This will be an array of objects containing Promises on which we want to call .all()
      filenames.each( function (filename) {
        files.push({content: fsPromise.readFileAsync(articlesPath + '/' + filename, 'utf8'), 
                   filename: filename});    
      });

This is an attempt to express what I want to do next:

      Promise.all(files).then( function(files) {
        return Lazy(files);
      });
    } 

, , promises, {content: "FILE CONTENTS", filename: "fileN.txt"}. - readFileAsync(), , , . , filenames.each() - , . , , . Lazy() - lazy.js, , .

-,

, .all() ? , promises , ? , , promises (.. , ). ?

,

.each()? .

filenames.each( function(filename) {
  files.push({content: fsPromise.readFileAsync(articlesPath + '/' + filename, 'utf8')
              .then( function(fulfilledContent) {return fulfilledContent}), 
              filename: filename
});

( , promises, - , , , , , )

+4
1

:

  • filenames . , , Promise.all :

    Promise.all(filenames.map(function(filename) {
        return fsPromise.readFileAsync(articlesPath + '/' + filename, 'utf8');
    })).then(function(contents) {
        return Lazy(contents).map(function(content, i) {
            return {content: content, filename: filenames[i]};
        });
    })
    
  • promises :

    Promise.all(filenames.map(function(filename) {
        return fsPromise.readFileAsync(articlesPath + '/' + filename, 'utf8').then(function(content) {
            return {content: content, filename: filename};
        });
    })).then(Lazy);
    
+5

Source: https://habr.com/ru/post/1629207/


All Articles