【发布时间】:2019-05-01 07:21:30
【问题描述】:
我正在尝试从第一次 axios 调用的结果进行 axios 调用,其中从第一次调用返回的数据是一个数组,我想迭代第一次 axios 调用的数组结果并为每个成员进行另一个 axios 调用的数组结果。每次 axios 调用完成后,我想在 Vue 模板中显示数据。所以基本上,第二个 axios 调用的结果也应该显示在第一个 axios 调用结果的列表项中。
处理此问题的最佳方法是什么?我尝试使用 async 和 await 并且在每个 axios 完成之前显示数据,并且第二个 axios 调用的结果没有显示在 Vue 组件中。
Vue 脚本:
getOffTheJobs(id, token) {
const self = this
const instance = axios.create();
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
instance.get(`${initialState.offTheJobApiBase}offthejob/${id}`, {
headers: {
'Authorization': token
}
})
.then(({data}) => {
if (data.hasOwnProperty('status') && data.status == 'success' && data.hasOwnProperty('data')) {
// Calculating total hours
data.data.activities.forEach(async (offTheJobAct) => {
self.totalOffTheJobActivityHours += offTheJobAct.totalHours;
if (offTheJobAct._id) {
await instance.get(`${initialState.offTheJobApiBase}activity/${offTheJobAct._id}`, {
headers: {
'Authorization': token
}
})
.then(({data}) => {
if (data.hasOwnProperty('status') && data.status == 'success' && data.hasOwnProperty('data') && !self.isEmptyArrayObject(data.data.activityEvidences)) {
self.offTheJobEvidences[offTheJobAct._id] = data.data.activityEvidences
}
}).catch((err) => {
console.warn(err.response.data.error)
})
}
})
self.offTheJobDetails = data.data
self.show = true
} else {
self.show = true
}
})
.catch((err) => {
console.warn(err)
this.showNotification('error', err.response.data.error)
})
},
Vue 组件代码:
<div class="block otj-detail" v-if="offTheJobDetails">
<h4>{{ offTheJobDetails.offTheJobTraining.name }} </h4>
<span>Total Required Hours: {{ offTheJobDetails.offTheJobTraining.totalHours }}</span>
<span>Total Hours Met: {{ totalOffTheJobActivityHours }}</span>
<div class="masterClasss" v-for='offTheJobActivity in offTheJobDetails.activities'>
<h5>Activity</h5>
<span class="block-detail">Name: {{ offTheJobActivity.name }}</span>
<span class="block-detail">Location: {{ offTheJobActivity.location }}</span>
<span class="block-detail">Hours Met: {{ offTheJobActivity.totalHours }}</span>
<div class="otj-detail-evidences" v-if="!isEmptyArrayObject(offTheJobEvidences) && offTheJobEvidences.hasOwnProperty(offTheJobActivity._id)">
<div class="col-md-3" v-for="activityEvidence in offTheJobEvidences[offTheJobActivity._id]">
{{ activityEvidence.evidenceDocument }}
</div>
</div>
</div>
</div>
【问题讨论】:
-
Promise.all() (也可以使用
fetch()进行http请求,不再需要axios) -
我可以将 Promise.all() 用于第二个请求,因为它们处于循环状态? @ChrisG
-
是的:构建一个请求对象数组,在其上调用 Promise.all() 并在其上调用
.then(resArray => {... })以获取结果。
标签: javascript vue.js ecmascript-6 vue-component es6-promise