What's wrong with the asynchronous implementation of asyncawit with permise?

methods: {
    getData() {
      if(!this.token) {
        console.log("token is null")
        return
      }
      let tokenBody = {
        "Content-Type": "application/json",
      }
      let itemsArr = []
      this.bymbolArr.forEach(async item => {
        console.log(item)
        let tokenBody = {
          "Content-Type": "application/json",
        }
        let data = await post(Config.getSharesUrl, tokenBody);
        if (data.RetrieveItem_Response_3) {
          let dataArr = data.RetrieveItem_Response_3.ItemResponse[0].Item[0].Fields.Field;
          if(dataArr.length > 0) {
            var obj = {}
            let arr = dataArr.forEach( item => {
              if(item.Double) {
                obj[item.Name] = item.Double
              }
            })
          }
        }
        let itemObj = {}
        itemObj[item] = obj
        console.log("itemibj="itemObj)
        itemsArr.push(itemObj)
      })
      console.log("itemsArr=" + itemsArr)
      this.items = itemsArr
    }

the post after await is used with ajax, encapsulated by permise with async and await. The result shows that itemsArr= is empty, and then each item of itemibj= is displayed. What is the cause?

Mar.28,2021

first of all, I don't understand the problem you described, but take a look at the code. Using async/await, in forEach means that each await is independent in a different async function, so we won't wait for each other. You can async getData () and then use the for loop instead of forEach.


do not have forEach or other encapsulation methods in async await .
you can use the original for loop or for of
or something like this

.
let each = async (arr,fn) => {
  for(var i=0;i<arr.length;iPP){
    await fn(arr[i],i);
  }
}

async getData(){
  let itemsArr = [];
    await each([1, 2, 3], async item => {
        var data = await post(item);
        itemsArr.push(data);
    });
    console.log(itemsArr)
}

because the outer function is not asynchronous, take a closer look at it.

Menu