forEach is not executed after the Axios asynchronous request ends

When I used Vue and Pinia together, I found that forEach was not executed after the Axios request ended. Later I found out that it was because the Axios request had not yet ended but forEach was executed first. At this time, the Axios request had not obtained any data, so forEach would An empty array is operated, but forEach will not execute the callback function for an empty array, so forEach is not executed at all.

The solution is to use Promise.all().then()

Code before modification

<script setup lang="ts">
import ...

// getWebInfoList方法继承自Store,是一个发起异步请求获取数据的方法
// 这里不用理解这个方法具体是干什么的,当作任意异步请求就行
webInfo.getWebInfoList();
webInfo.webInfoList.forEach((item: any) => {
  console.log("forEach执行了")
})
<script>

Modified code

<script setup lang="ts">
import ...

// getWebInfoList方法继承自Store,是一个发起异步请求获取数据的方法
// 这里不用理解这个方法具体是干什么的,当作任意异步请求就行
webInfo.getWebInfoList().then(() => {
  Promise.all(webInfo.webInfoList).then(() => {
    webInfo.webInfoList.forEach((item: any) => {
      console.log("forEach执行了")
    })
  })
})
<script>

Guess you like

Origin blog.csdn.net/Coin_Collecter/article/details/132892352