我如何等待循环中的所有axios请求完成?
这是我的代码:
async uploadMedia({ getters, commit }, payload) {
await commit('setUploadLoading', true)
const upload = new Promise((resolve) => {
payload.forEach((item, index) => {
const form = new FormData()
form.append('file', payload[index])
form.append('token', getters.getCustomerToken)
form.append('no', index)
this.$axios
.post(`${process.env.API_URL}/visa/uploadfile`, form, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(() => resolve())
})
})
await upload.then(() => commit('setUploadLoading', true))
await upload.finally(() => commit('setUploadLoading', false))
}
我在此循环中发出了2个请求,但我不知道如何等待所有请求完成。
答案 0 :(得分:1)
使用Promise.all
async uploadMedia({ getters, commit }, payload) {
await commit('setUploadLoading', true)
const upload = new Promise((resolve) => {
const unresolvedPromises = [] // array of promises
payload.forEach((item, index) => {
const form = new FormData()
form.append('file', payload[index])
form.append('token', getters.getCustomerToken)
form.append('no', index)
const promise = this.$axios
.post(`${process.env.API_URL}/visa/uploadfile`, form, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
unresolvedPromises.push(promise) // push promise to array
})
const resolvedPromises =
Promise.all(unresolvedPromises).then(res => console.log(res)) // wait for all promises to be resolved
})
await upload.then(() => commit('setUploadLoading', true))
await upload.finally(() => commit('setUploadLoading', false))
}
docs:https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Promise/all