我正在尝试一些涉及 Promise 的异步调用(AXIOS
调用)。代码的问题是在 this.updateUsers()
和 this.updateEmails()
执行并完成之前调用 this.reloadData()
。等待两个函数完成然后调用 this.reloadData() 的正确方法是什么?
rest.putEmail
和 rest.putUser
都是 axios REST API 调用。
mainFunc() {
Promise.all([this.updateUsers(), this.updateEmails()]).then(() => {
this.reloadData();
})
}
updateEmails() {
const {emails} = this.state;
if (emails.length > 0) {
emails.map(user => {
rest.putEmail(email.id, email.content)
.catch(err => {this.error(err)});
});
}
}
updateUsers() {
const {users} = this.state;
if (users.length > 0) {
users.map(user => {
rest.putUser(user.id, user.name)
.catch(err => {this.error(err)});
});
}
}
最佳答案
如评论中所述,您的 updateEmails()
和 updateUsers()
函数不返回 promise ,并且 Promise.all
接受数组 promise 作为参数。在本例中,您将 undefined 作为参数传递给 Promise.all
,因此它不会等待 updateEmails()
或 updateUsers()
> 执行。
要解决此问题,您需要将所有 Promise 调用放入一个数组中,将该数组提供给 Promise.all
,然后在 updateEmails()
中返回该数组。 code> 和 updateUsers()
函数。
mainFunc() {
Promise.all([this.updateUsers(), this.updateEmails()]).then(() => {
this.reloadData();
})
}
updateEmails() {
const {emails} = this.state;
if (emails.length > 0) {
const promises = emails.map(user => {
rest.putEmail(email.id, email.content)
.catch(err => {this.error(err)});
});
return Promise.all(promises);
}
}
updateUsers() {
const {users} = this.state;
const promises = [];
if (users.length > 0) {
const promises = users.map(user => {
rest.putUser(user.id, user.name)
.catch(err => {this.error(err)});
});
return Promise.all(promises);
}
}
每当您在 emails 和 users 数组上调用 .map
时,都会返回一个 Promise 数组,该数组存储在两个函数的 const Promise
中。现在,您只需将这些 Promise 传递给 Promise.all
并返回从 Promise.all
返回的 Promise。现在,您的 mainFunc()
内部的 Promise.all
调用正在接收需要等待的 promise ,并且不会调用 this.reloadData()
直到两个函数都执行完毕。
关于javascript - Promise.all 不等待函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50994427/