0

I have a method sending API request in loop of list, after the loop I would like to update view on the screen, but this update is not waiting for the end of the last post. Any suggestions?

async doPost(name) {
    return await axios.post("/api/data/" + name);
}

async doAction(dataList) {
    dataList.map(dt=> {
      const actionResponse = this.doPost(dt.name);
      if (actionResponse) {
        console.log("response: " + actionResponse);
        this.updateNotify(dt);
      }
  });
  this.UpdateView();
};

2 Answers 2

1

I think you missed the awaitkeyword before this.doPost()

async doPost(name) {
    return await axios.post("/api/data/" + name);
}

async doAction(dataList) {
   const dtData =  dataList.map(async dt=> {
      const actionResponse = await this.doPost(dt.name);
      if (actionResponse) {
        console.log("response: " + actionResponse);
        return dt;
       // this.updateNotify(dt);
      }
  });

  const data = await Promise.all(dtData);
  this.updateNotify(data)

  this.UpdateView();
};
Sign up to request clarification or add additional context in comments.

3 Comments

But await operator in that place is not compiled: The await operator can only be used in an async function.
But inside the loop it is not working, not even compiled
I have updated my answer (untested code), please take a look.
0

Axios library by default returns promise like object - AxiosPromise<any>, so making the function "doPost" async with await in it will results in Promise<AxiosPromise<any>> type. That's why I changed it to non-async, cause it is not needed here.

doPost(name) : AxiosPromise<any> {
     return axios.post("/api/data/" + name);
}

async doAction(dataList: { name: string }[]) {
    const dtData: AxiosPromise<any>[] = dataList
        .map(dt => axios.doPost(dt.name)) // creating all post requests
        .map(x => x.then(x => this.updateNotify(x))); // setting updateNotiFy to  execute when post request returns result

    // Makes sure all executions of post requests are done(resolved/rejected)
    await Promise.allSettled(dtData);

    this.UpdateView();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.