map中如何使用 async await

782 阅读1分钟

这是我第一次写文章,写的不好,望大家多多支持!!!

最近在工作中遇到一个问题,正好记录一下,如果你也想以后少踩坑,那就点继续往下看吧。

今天遇到一个业务场景,正好就用到了这个知识点:批量新增数据功能, 输入多个项目id后,请求数据,后端返回项目信息【数组对象】,但是每个项目下,都有对应的一个项目阶段属性select 下拉(并没有在查询的时候一起返回,比较坑!),这个就要我们再次的通过项目id去请求接口,然后前端我们自己合并一个新的数组对象来用。 看代码!

实际的业务场景要比我描述的还要复杂,看重点就好了 加油

   batchConfirm() {
      // 拆分获取的字符串 
      const str = this.batchData.trim()
      const arr = str.split(/\n/g)
      const projectIds = []
      const arrObj = arr.map(item => {
        const itemArr = item.split(/\s+/)
        projectIds.push(Number(itemArr[0]))
        return { id: itemArr[0], amount: itemArr[1] }
      })
      // 请求接口,获取匹配id的数据list
      batchInvoies(
        projectIds,
        this.applyForm.clientId,
        this.applyForm.currencyId
      ).then(res => {
        res.data.map(item => {
          arrObj.filter(obj => {
            if (item.id === obj.id) {
              // 对象合并
              return Object.assign(item, obj)
            }
          })
        })

重点:我们知道 map函数里面的方法是同步的,那我们要是想在map中实现异步请求,如何实现呢? 异步请求用async await ,async 返回的是Promise。

        // 重点
        Promise.all(
          // 通过id 获取每一项下的阶段list (select下拉功能)
          res.data.map(async item => {
            const fee = item.currencyId === 1 ? item.fee : item.foreignFee
            const waitCome = fee - item.invoice
            var stageList = []
            // 发送请求
            await getStageList({ projectId: item.id }).then(res => {
              stageList = res.data
            })
            return {
              stageList: stageList,
              projectId: item.id,
              fee: fee,
              waitCome: waitCome,
              amount: item.amount
            }
          })
        ).then(res => {
          if (
            this.applyForm.projectsDetailList.length === 1 &&
          !this.applyForm.projectsDetailList[0].projectId
          ) {
            this.applyForm.projectsDetailList = res
          } else {
            this.applyForm.projectsDetailList.push(...res)
          }
          this.getTotal()
          this.dialogVisible = false
        })
      })
    },

哈哈,这样就实现我们想要的效果了。

是不是很简单,感觉对你有帮助的话,别忘了点赞哦,知识在于积累,加油吧!!!