forEach 和 for...of... 在遍历内部存在异步操作的区别

发布于:2024-08-08 ⋅ 阅读:(129) ⋅ 点赞:(0)

起先是因为一段代码:

const formatUserInfo = async (id) => {
  const result = await getUserInfoByIdAPI(id)
  return result.data.data
}
const getReturnSchoolInfoList = async () => {
  const result = await getReturnSchoolInfoListAPI(page.value, limit.value)
  count.value = result.data.data.count
  returnSchoolInfoList.value = result.data.data.rows
  // todo 根据userId 获取用户信息 并与返校信息合并
  returnSchoolInfoList.value.forEach(item => {
    const result1 = await formatUserInfo(item.userId)
    console.log(result1)
    item.userInfo = result1
  })
  console.log(returnSchoolInfoList.value)
}

然后报错: [vite] Internal server error: [vue/compiler-sfc] Unexpected reserved word ‘await’.。

如果去掉 await ,那么由于是异步操作会先输出 returnSchoolInfoList.value,再输出 result1,并且因为赋值的时候并没有获取到result1 的具体值,所以需等待该异步操作完成后再进行赋值。

然后幸好有 Webstorm 的智能提示,让我使用 for…of… 代替 forEach,bug 果然消失了 !

const formatUserInfo = async (id) => {
  const result = await getUserInfoByIdAPI(id)
  return result.data.data
}
const getReturnSchoolInfoList = async () => {
  const result = await getReturnSchoolInfoListAPI(page.value, limit.value)
  count.value = result.data.data.count
  returnSchoolInfoList.value = result.data.data.rows
  // todo 根据userId 获取用户信息 并与返校信息合并
  for (const item of returnSchoolInfoList.value) {
    const result1 = await formatUserInfo(item.userId)
    console.log(result1)
    item.userInfo = result1
  }
  console.log(returnSchoolInfoList.value)
}

并且等待异步完成后,正确赋值了!


网站公告

今日签到

点亮在社区的每一天
去签到