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.
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)
}))