【问题标题】:How to make subsequent axios call for the array result of the first axios call?如何对第一次axios调用的数组结果进行后续的axios调用?
【发布时间】: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 =&gt; {... }) 以获取结果。

标签: javascript vue.js ecmascript-6 vue-component es6-promise


【解决方案1】:

这应该可以,但无法测试。代码可能有点干了。

async getOffTheJobs(id, token) {
    const self = this
    const instance = axios.create();
    delete instance.defaults.headers.common['X-CSRF-TOKEN'];

    const opts = {
        headers: { 'Authorization': token }
    }
    const url = `${initialState.offTheJobApiBase}offthejob/${id}`
    const { data } = await instance.get(url, opts)

    if (!(data.status && data.status == 'success' && data.data)) {
        self.show = true
        return
    }

    // Calculating total hours
    const { activities } = resp.data
    const p = activities.map(async (offTheJobAct) => {
        self.totalOffTheJobActivityHours += offTheJobAct.totalHours;
        if (offTheJobAct._id) {
            try {
                const url = `${initialState.offTheJobApiBase}activity/${offTheJobAct._id}`
                const { subData } = await instance.get(url, opts)
                if (subData.status && subData.status == 'success' && subData.data && 
                    !self.isEmptyArrayObject(subData.data.activityEvidences)) {
                    self.offTheJobEvidences[offTheJobAct._id] = subData.data.activityEvidences
                }
            } catch (err) {
                console.warn(err.response.data.error)
            }
        }
    })

    await Promise.all(p)
    self.offTheJobDetails = data.data
    self.show = true
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多