Invader
Invader

Reputation: 161

How to resolve pending promises within map returning an object?

This would resolve all promises

const promises = files.map(filename => getPdfToPrint(`output\\${outputDirectory}\\` , filename.replace("/", "")));
const res = await Promise.all(promises)

but now the files.map function should map the filename to an object like this

const promises = files.map(filename => { return {status: getPdfToPrint(`output\\${outputDirectory}\\` , filename.replace("/", "")), filename: filename}});
const res = await Promise.all(promises)

in order to check whether the promise resolved "success" so that I know which files were retrieved and printed. But in this way the Promise resolving the status would still be pending. How would I solve this problem?

Upvotes: 2

Views: 353

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

If I understand correctly, your getPdfToPrint() returns a promise. At the moment you're mapping each filename to the promise returned by getPdfToPrint(), but instead you want to have the resolved value in an object at the key status along with the filename. To achieve that, you can make your .map() callback async. This will do two things: firstly, it will enable you to await the getPdfToPrint() function Promise to get the resolved value so you can use that inside of the object you're returning. Secondly, it will make it so that your callback function returns a Promise (as all async functions return a Promise). This will allow you to use Promise.all() to detect once all the promises have resolved:

const promises = files.map(async filename => {
  const pdf = await getPdfToPrint(`output\\${outputDirectory}\\` , filename.replace("/", ""));
  return {status: pdf, filename}; 
});
const res = await Promise.all(promises);

Upvotes: 3

Related Questions