Javascript 一旦完成多个嵌套forEach循环中的所有异步操作,如何解析promise?
我在一个异步函数中有一个forEach循环,在这个forEach循环中有两个额外的forEach循环,它们执行AJAX请求。我希望在所有AJAX请求完成后返回一个已解决的承诺 首先,用户单击“提交”,我调用一个函数来处理提交,将Javascript 一旦完成多个嵌套forEach循环中的所有异步操作,如何解析promise?,javascript,Javascript,我在一个异步函数中有一个forEach循环,在这个forEach循环中有两个额外的forEach循环,它们执行AJAX请求。我希望在所有AJAX请求完成后返回一个已解决的承诺 首先,用户单击“提交”,我调用一个函数来处理提交,将submitting属性设置为true。提交完成后,我想更改submitting属性的值 submit() { this.submitting = true; if (creating) { this.create().then(() => thi
submitting
属性设置为true
。提交完成后,我想更改submitting
属性的值
submit() {
this.submitting = true;
if (creating) {
this.create().then(() => this.submitting = false)
}
}
下面是create()
方法的近似值:
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');
}
我尝试了几种不同的解决方案,使用map()
捕获承诺,并使用Promise.all在所有承诺完成后执行回调,但我没有成功。我认为这个问题源于我有多个嵌套的forEach()
循环,但我对承诺(以及它们在forEach()
循环中的行为)的理解不够透彻,无法确定
我的理解是,我可以在for…of
循环中使用wait
,但如果可能的话,我更愿意并行执行AJAX请求
谢谢
编辑:建议的副本类似,但我的问题是关于嵌套
forEach
循环中的异步操作。虽然解决方案表明处理这些情况没有什么特别的独特之处(对父循环和嵌套循环都执行相同的操作),但确定这是否是问题的动机。将
映射到承诺,然后使用Promise.all并等待它们:
await Promise.all(user.images.map(image =>
axios.post('/images', image)
));
这同样适用于主forEach:
await Promise.all(this.users.map(async user => {
//...
}));
谢谢我曾在内部
forEach
循环上尝试过,但也需要将其添加到主forEach
循环才能使其工作。我还必须添加Promise.resolve()。