node.js - Promise.all 不返回 res map nodejs
问题描述
我们正在与 Outlook api 集成,我们需要对恢复的电子邮件中的附件进行分组:
我们正在尝试这种方式:
const result = await client
.api('/me/messages')
.filter(searchMailFrom)
.select('subject, from, receivedDateTime, sentDateTime, isRead, toRecipients, hasAttachments')
.get()
let dadosAnexo = result.value.map(async item => {
if (item.hasAttachments) {
const resultAtt = await client
.api('/me/messages/' + item.id + '/attachments')
.get()
item.anexos = resultAtt.value
}
})
await Promise.all(dadosAnexo)
return res.status(200).send(result.value)
但是当我们放入 Promise.all() 时,系统干脆什么都不返回
解决方案
您没有从.map
函数内部返回任何内容。因此,dadosAnexo
成为一个Promise
s 数组,每个都将解析为undefined
。
查看 MDN 文档以获取有关其.map
工作原理的更多详细信息:Map | MDN。
然后,您将传递dadosAnexo
给您的Promise.all
电话。
但是当我们放入 Promise.all() 时,系统干脆什么都不返回
在这里,你的假设是错误的。
await Promise.all(dadosAnexo)
上面的await Promise.all
调用实际上将返回一个undefined
. 因为您正在传递它dadosAnexo
(一个 s 数组Promise
,每个都解析为undefined
)。此外,您没有将返回值分配给任何变量(因此,您实际上并不知道它是否返回了某些东西)。
查看 MDN 文档以获取有关其Promise.all
工作原理的更多详细信息:Promise.all() | MDN
现在要解决您的问题,这里有一个解决方案:
const result = await client
.api('/me/messages')
.filter(searchMailFrom)
.select('subject, from, receivedDateTime, sentDateTime, isRead, toRecipients, hasAttachments')
.get()
// promisesToAttach will be an array containing some Promises and some item values
const promisesToAttach = result.value.map(item => {
if (item.hasAttachments) {
// returning a promise
return client
.api('/me/messages/' + item.id + '/attachments')
.get()
.then(resultAtt => {
item.anexos = resultAtt.value
return item
})
}
// returning an item value
return item
})
// resultWithAttachments will be an array of resolved item values
const resultWithAttachments = await Promise.all(promisesToAttach)
return res.status(200).send(resultWithAttachments)
推荐阅读
- javascript - Typescript/Javascript - 使用 new String() 和 s = '' 来声明变量
- python - 有没有办法将 i = 0 的值带到另一个 Python 文件?
- pandas - 如何将左联接与两个单独的列名合并并仅从左表中获取列
- amazon-web-services - AWS opswork 云形成无法导入
- uml - 这个序列的最佳 UML 图是什么?
- python - 如何修改 Keras 中自定义循环层的输出形状?
- opencv - 我可以使用哪个宏定义来检查我的 OpenCV 库是否支持 cv::imshow 接口?
- android - 设置提示时 EditText 不扩展
- c# - C# 抽象/反射和 DbSet
- database - 用普通网站(bbs、博客、新闻...)进行低成本的 aws dynamodb 设计是不可能的吗?