Carlos Martinez Carlos Martinez - 5 months ago 17
Javascript Question

Map filename with promise contents result

I'm using bluebird for promises and I'm trying to get the contents for multiple files; what I want is to be able to get the contents for a file together with its filename, e.g:

result = { 'file1.md': content }


I've been trying something like this:

var files = [
{ filename: 'README.md', url: 'assetFiles/README.md' },
{ filename: 'CHANGELOG.md', url: 'assetFiles/CHANGELOG.md' },
{ filename: 'ISSUES_TEMPLATE.md', url: 'assetFiles/ISSUES_TEMPLATE.md' },
{ filename: 'PULL_REQUEST_TEMPLATE.md', url: 'assetFiles/PULL_REQUEST_TEMPLATE.md' }];

return Promise.all(files.map(function(file) {
return [file.filename, fs.readFileAsync(file.url, 'utf-8')];
}))
.then(function(results){
console.log(results);
};


however, what i'm getting from this is an array like:

result = [ ['file1.md', Promise ], ... ];


How can I get the filenames together with the contents of the file using bluebird?

Answer

To avoid having to create a new promise (the so-called "promise constructor anti-pattern"):

return Promise.all(files.map(function(file) {
  return fs.readFileAsync(file.url, "utf-8")
    .then(data => [file.filename, data]);
  }))  
  .then(function(results){
    console.log(results);
  })
  .catch(function(err) {
    console.log(err);
  });
Comments