I have a forEach loop inside an async function, and inside that forEach are two additional forEach loops that perform AJAX requests. I want to return a resolved promise once all of the AJAX requests are complete.
First, the user clicks "Submit" and I call a function to handle submission, setting the submitting
property to true
. Once the submission is complete, I want to change the value of the submitting
property.
submit() {
this.submitting = true;
if (creating) {
this.create().then(() => this.submitting = false)
}
}
Here's an approximation of the create()
method:
async create() {
// Calls a function that uses axios to send a POST request to create
// a new group, returning its ID upon completion. This works fine.
const groupId = await this.createGroup();
// 'users' is an array of objects
this.users.forEach(async user => {
// Create a new user and get their ID. This works fine.
const userId = await this.createUser(info);
// Each 'user' object contains a key called 'attributes' whose
// value is an array of 'attribute' objects. I use axios to make a
// POST request to store the info about these attributes in the DB.
user.attributes.forEach(attribute => {
axios.post('/attributes', attribute)
// In my application, I'm actually calling a method that handles
// making the request, so it looks more like this:
// this.createAttributes(attribute)
}
// Each 'user' object also contains a key called 'images' whose
// value is an array of 'image' objects. Here again, I use axios to
// make a POST request to store the info about these images.
user.images.forEach(image => {
axios.post('/images', image)
}
}
// Once everything has successfully posted, I want to return a
// resolved promise so that the then() callback on my create method
// is executed. However, anything here gets executed before the AJAX
// requests complete.
console.log('All done');
}
I've tried a few different solutions I've come across for capturing promises using map()
and using Promise.all to execute a callback once they're all complete, but I haven't had success with that. I think the issue stems from my having multiple nested forEach()
loops, but I don't understand promises (and their behavior within forEach()
loops specifically) well enough to know for sure.
It's also my understanding that I can use await
inside a for...of
loop, but I would prefer to execute the AJAX requests in parallel if possible.
Thanks!
Edit: The proposed duplicate is similar, but my question was specifically about async operations within nested forEach
loops. While the solution revealed that there is nothing particularly unique about handling these cases (do the same thing on both the parent and nested loop), determining whether this was the case was the motivation for asking the question.