forEach异步调用问题

908 阅读1分钟

背景

在forEach中使用异步函数,会导致执行到await时跳出循环

1742906-20220311151527211-428402384.png

解决办法

第一种:使用for循环

      const images: Array<object> = []
      for (const { originFileObj } of fileList) {
        images.push({ src: await getBase64(originFileObj) })
      }

第二种:使用Promise.all与map结合

      const images = await Promise.all(
        fileList.map(async (item: any) => ({ src: await getBase64(item.originFileObj) }))
      )

参考:www.jianshu.com/p/2e5734425…