Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Waiting for series of axios calls to return

I’m writing a React application for submitting timesheets, and having an issue when trying to submit a bunch of entries at once. Each entry has to be submitted in a separate API call, so what I have so far looks like this. This is inside a redux Thunk if that helps as well.

var foo = new Promise((resolve, reject) =>{
    timesheets.forEach(timeentry => {
        api_function = 'XXXXXX' // string for submitting 1 entry
  
        axios.post(url, api_function);
    }
})

The idea is that once all of these are posted, I can do another call to refresh the timesheet data I have to display for the frontend. The problem I’m running into, is that not all of the posts are posting properly, sometimes only 2-3 of them go through.

I have done some console logging to see that the forEach loop is running the correct amount of times, and that the api_function string is sending the correct data in each of those loops.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am not sure the logic of which entries are sending properly and which are not, as its not always the first 2-3 that work, but seemingly chooses which ones go through at random.

If there is a better way to be doing this, that would also be greatly appreciated, to summarize, I’m looking for a way to call a series of POST api calls, wait for them all to be done, then make a get call to refresh that data

>Solution :

What you need is an Promise.all()

var foo = Promise.all(timesheets.map(timeentry => {
   api_function = "xxxx"
   return axios.post(url, api_function)
}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading