首页 > 解决方案 > 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() 时,系统干脆什么都不返回

标签: node.jsasync-awaitoutlook-restapi

解决方案


您没有从.map函数内部返回任何内容。因此,dadosAnexo成为一个Promises 数组,每个都将解析为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)

推荐阅读