如何在返回对象的地图中解决未决承诺?

发布于 2025-01-19 17:10:23 字数 552 浏览 2 评论 0原文

这将解决所有承诺,

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

但现在 files.map 函数应该将文件名映射到这样的对象,

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

以便检查承诺是否解决“成功”,以便我知道哪些文件被检索和打印。但这样解决状态的 Promise 仍然处于待处理状态。 我该如何解决这个问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪落纷纷 2025-01-26 17:10:23

如果我正确理解,您的getpdftoprint()返回承诺。目前,您将每个文件名映射到> getpdftoprint() 的承诺中状态以及文件名。为此,您可以使您的.map()回调async。这将做两件事:首先,它将使您能够等待 getpdftoprint()函数有望获得解决值,以便您可以在对象内部使用该值,重新返回。其次,它将使您的回调函数返回承诺(因为所有async函数返回承诺)。这将允许您使用Promise.all()来检测所有承诺一旦解决:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文