如何从嵌套的承诺中获取最终承诺链中的数据

时间:2020-10-20 21:33:00

标签: javascript async-await

所以我正在调用函数fetchTaskLeads。在其中,即时通讯返回了承诺。但是这个诺言数组,因为每个诺言都有嵌套的诺言数组,所以我想在其中获取数据。

问题是我的undefined的最后一个.then块有parsedLeadsWithContacts。为什么会这样?

const test = fetchTaskLeads(leads)

const fetchTaskLeads = (leads) => {
  if (!isEmpty(leads)) {
    const parsedLeads = []

    return Promise.all(leads.map((l) => db.collection('leads').doc(l).get()))
      .then((fetchedLeads) => {
        parsedLeads = fetchedLeads.map((l) => ({ leadId: l.id, ...l.data() }))

        return Promise.all(parsedLeads.map((pl) => fetchTaskContacts([pl.contact.cardId])))
      })
      .then((parsedLeadsWithContacts) =>
        parsedLeads.map((pl, index) => ({ leadId: pl.leadId, ...parsedLeadsWithContacts[index][0] })),
      )
  }
  return []
}

1 个答案:

答案 0 :(得分:0)

我认为最后一部分应该是:

      ...
      .then((parsedLeadsWithContacts) => {
        // add return keyword, and rewrite with full braces to see what is going on:
        return parsedLeads.map((pl, index) => ({
          leadId: pl.leadId,
          ...parsedLeadsWithContacts[index][0]
        })) //, and take off the ending comma
      })