【问题标题】:Map inside map async await地图内的地图异步等待
【发布时间】:2022-02-04 02:43:53
【问题描述】:

我必须使用async/await 覆盖地图。

我想知道,如果我等待主要的Promise.all,它是否也会等待重叠的承诺?

const upsertPromises = body.schedules.map(async schedule => {
    const createdSchedule = await this.addSchedule(briefId, schedule.week_day.id)
    schedule.exclusions.map(async exclusion => {
        await this.addScheduleExclusions(createdSchedule.id, exclusion.from.id, exclusion.to.id)
    })
})
await Promise.all(upsertPromises)

在此代码上,this.addScheduleExclusions 是否在最后一行 Promise.all(upsertPromises) 之后完成?

【问题讨论】:

  • .map() 仅在其函子返回某些内容时才有意义,因此在每个函子内添加一对或返回 ... 一个。 upsertPromises 将是一个或多个 promise 数组。如果您只对完成而不是值感兴趣,那么只需等待(或返回)Promise.all(upsertPromises.flat())(您可能需要 polyfill 用于 .flat())。

标签: node.js async-await promise


【解决方案1】:

如果 async 函数中的所有 promise 前面都有 await,那么 async 函数将:

  • 在所有等待解决时解决
  • 如果有任何等待被拒绝,则拒绝。

如果您使用array.map 运行此函数,您将获得可以解决与否的承诺。

Promise.all 将返回执行以下操作之一的承诺:

  • 如果全部解决,则解析结果数组
  • --或--
  • reject with first error that denied
const upsertPromises = body.schedules.map(async schedule => {
    // awaited - ok
    const createdSchedule = await this.addSchedule(briefId, schedule.week_day.id)
    
    // Not awaited! 
    // schedule.exclusions.map( async exclusion => {
    // - need to add another `await` here like this:

    await Promise.all(schedule.exclusions.map( async exclusion => {
        // awaited - ok
        await this.addScheduleExclusions(
            createdSchedule.id, exclusion.from.id, exclusion.to.id
        )
    })
})

await Promise.all(upsertPromises)

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多