Vuejs asyncData函数中的嵌套Promise

问题描述 投票:1回答:2

让我们把它煮到最低限度。

我这里有一个小组件从服务器获取数据。与此组件和任何其他组件的区别在于它必须执行两次AJAX调用。一个接一个地!

<template>
    <div>Easy</div>
</template>

<script>

    import axios from 'axios'

    let firstFetch = () => {
        return axios.get('/first')
    }

    let secondFetch = () => {
        return axios.get('/second')
    }

    export default {
        name: 'p-components-accordion-box',
        methods: {
            setActive(index) {
                this.$emit('setActive', index)
            }
        },
        asyncData({store, route, router}) {
            return new Promise((resolve, reject) => {
                firstFetch()
                .then((result) => {
                    secondFetch()
                    .then((result) => {
                        resolve()
                    })
                    .catch((error) => {
                        throw { url: '/404' };
                    })
                })
                .catch((error) => {
                    throw { url: '/404' };
                })
            })
        }

    }

</script>

<style>


</style>

事情是这项工作完美是所有要求工作。但如果出现问题,我会:

throw { url: '/404' };

它在浏览器中工作得很完美,这意味着我转到'/ 404'但是在NodeJS上我一直收到这条消息。

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误源于在没有catch块的情况下抛出异步函数,或者拒绝未使用.catch()处理的promise。 (拒绝ID:1)

有没有人做过类似的事情?

vuejs2 es6-promise vuex vue-ssr
2个回答
3
投票

而不是把错误扔进asyncData,试着拒绝承诺:

export default {
    name: 'p-components-accordion-box',
    methods: {
        setActive(index) {
            this.$emit('setActive', index)
        }
    },
    asyncData({store, route, router}) {
        return new Promise((resolve, reject) => {
            firstFetch()
            .then((result) => {
                secondFetch()
                .then((result) => {
                    resolve()
                })
                .catch((error) => {
                    reject()
                })
            })
            .catch((error) => {
                reject()
            })
        })
    }
}

然后,无论何时使用该方法,您都可以捕获并处理错误:

this.asyncData(.....)
    .then(.....)
    .catch(error => { 
        throw { url: '/404' }
    })

0
投票

最后,这似乎工作正常。这不是样板,而是最终的代码。

Component.vue - asyncData()

asyncData({store, route, router}) {

            let data = {
                ca: route.params.ca,
                province: route.params.province,
                locality: route.params.locality,
            }

            return store.dispatch('FETCH_MAP_COORDINATES_AND_PROPERTIES', data)
            .catch(() => {
                if (process.browser) {
                    router.push('/404')
                }else{
                    console.log("beforeThrow1");
                    throw { url: '/404' };
                }
            })
    }

这是我的FETCH_MAP_COORDINATES_AND_PROPERTIES动作

let FETCH_MAP_COORDINATES_AND_PROPERTIES = ({commit, dispatch, state}, data) => {

    return new Promise((resolve, reject) => {
        fetchMapCoordinatesV2(data, state.axios)
        .then((result) => {

            if (result.status !== 200) {
                logger.error({
                    key: 'src.api.map.fetchMapCoordinates.then.badResponse',
                    data: result.data
                })

                reject(result)
            }

            logger.info({
                key: 'src.api.map.fetchMapCoordinates.then',
            })

            result = result.data

            let center = {
                lat: result.location.data.geocode.data.lat,
                lon: result.location.data.geocode.data.lon
            }
            let zoom = result.location.data.zoom

            commit('SET_PROPERTY_MAP_CENTER', result.location.data.geocode.data )
            commit('SET_PROPERTY_MAP_BOUNDS', result.location.data.geocode )

            let default_coords = {
                ne: {
                    lat: result.location.data.geocode.data.ne_lat,
                    lon: result.location.data.geocode.data.ne_lon,
                },
                nw: {
                    lat: result.location.data.geocode.data.nw_lat,
                    lon: result.location.data.geocode.data.nw_lon,
                },
                se: {
                    lat: result.location.data.geocode.data.se_lat,
                    lon: result.location.data.geocode.data.se_lon,
                },
                sw: {
                    lat: result.location.data.geocode.data.sw_lat,
                    lon: result.location.data.geocode.data.sw_lon,
                }
            }

            fetchMapProperties(default_coords, state.axios)
            .then((result) => {
                logger.info({
                    key: 'store.actions.map.index.FETCH_MAP_PROPERTIES.then',
                    data: result.data
                })

                commit('SET_MAP_PROPERTIES', result.data)
                resolve(result.data)
            })
            .catch((error) => {

                logger.error({
                    key: 'src.api.map.fetchMapProperties.catch',
                    coords: default_coords,
                    data: error
                })

                reject(error)
            })
        })
        .catch((error) => {
            logger.error({
                key: 'src.api.map.fetchMapCoordinatesV2.catch',
                data: error
            })

            reject(error)
        })
    })



};

这些是我的两种获取方法:

let fetchMapCoordinatesV2 = (data, axios) => {

    let query = '';
    if (data.ca) query = query + `/${data.ca}`
    if (data.province) query = query + `/${data.province}`
    if (data.locality) query = query + `/${data.locality}`

    logger.info({
        key: 'fetchMapCoordinatesV2',
        query: query
    })

    return axios.get(`/locations${query}`)

}

let fetchMapProperties = (coords, axios) => {

    return new Promise((resolve, reject) => {

        axios.post(`/properties/map`, coords)
        .then((result) => {

            logger.info({
                key: 'src.api.map.fetchMapProperties.then',
                coords: coords
            })

            resolve(result)
        })
        .catch((error) => {

            logger.error({
                key: 'src.api.map.fetchMapProperties.catch',
                coords: coords,
                data: error.response
            })

            reject(error)
        })

    });

}

它现在工作得很好,如果两个调用都成功,它会正确呈现,如果任何http调用失败或收到非200状态代码,它会呈现/ 404。

© www.soinside.com 2019 - 2024. All rights reserved.