[英]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但现在files.map
function 应该 map 文件名到 object 这样
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.为了检查 promise 是否解决了“成功”,以便我知道检索和打印了哪些文件。 But in this way the Promise resolving the status would still be pending.但是这样Promise解析状态还是pending。 How would I solve this problem?我将如何解决这个问题?
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
.如果我理解正确,您的getPdfToPrint()
返回 promise。目前您正在将每个filename
映射到getPdfToPrint()
返回的 promise,但是您希望在 object 中的关键status
以及filename
。 To achieve that, you can make your .map()
callback async
.为此,您可以使.map()
回调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.这将做两件事:首先,它将使您能够await
getPdfToPrint()
function Promise 以获取已解析的值,以便您可以在要返回的 object 中使用它。 Secondly, it will make it so that your callback function returns a Promise (as all async
functions return a Promise).其次,它将使您的回调 function 返回 Promise(因为所有async
函数都返回 Promise)。 This will allow you to use Promise.all()
to detect once all the promises have resolved:这将允许您使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.