programing

Vuex 디스패치에 의한 비동기/대기

procenter 2022. 7. 21. 23:14
반응형

Vuex 디스패치에 의한 비동기/대기

앱에 있는 몇 가지 컴포넌트의 로더를 만들고 있습니다.

내 컴포넌트는 다음과 같습니다.

        mounted() {
            this.loading = true;

            this.getProduct();
        },
        methods: {
            async getProduct() {
                await this.$store.dispatch('product/getProducts', 'bestseller');

                console.log(123);

                this.loading = false;
            }
        },

Vuex 액션:

getProducts({commit}, type) {
        axios.get(`/api/products/${type}`)
            .then(res => {
                let products = res.data;
                commit('SET_PRODUCTS', {products, type})
            }).catch(err => {
            console.log(err);
        })
    },

문제는 다음 행에 있습니다.await this.$store.dispatch('product/getProducts', 'bestseller');

코드가 그 라인에서 정지하고 AJAX 콜에서 데이터가 로드되기를 기다렸다가 로딩이 다음과 같이 설정될 것으로 예상합니다.false;

하지만 그렇지는 않다.로딩이 아직 설정되었습니다.false및 그console.log데이터가 준비되기 전에 실행할 수 있습니다.

이미 비동기/대기 상태를 Vuex 작업으로 이동하려고 시도했지만 정상적으로 작동했습니다.하지만 나는 그들 사이의 차이를 이해하지 못했다.

아래 코드는 나에게 유효합니다.

컴포넌트:

mounted() {
            this.loading = true;

            this.$store.dispatch('product/getProducts', 'bestseller').then((res) => {
                this.loading = false;
            });
        },

Vuex 액션:

async getProducts({commit}, type) {
        let res = await axios.get(`/api/products/${type}`);

        commit('SET_PRODUCTS', {products: res.data, type});
    }

변경:

getProducts({commit}, type) {
    axios.get(`/api/products/${type}`)
        .then(res => {
            let products = res.data;
            commit('SET_PRODUCTS', {products, type})
        }).catch(err => {
        console.log(err);
    })
},

이를 위해:

getProducts({commit}, type) {
    return axios.get(`/api/products/${type}`)
        .then(res => {
            let products = res.data;
            commit('SET_PRODUCTS', {products, type})
        }).catch(err => {
        console.log(err);
    })
},

될 거야.

axios.get약속을 반환합니다.그 약속을 돌려주셔야 합니다await기다려봐.그렇지 않으면 암묵적으로 반환됩니다.undefined그리고.await undefined즉시 해결됩니다.

약속 없이 행사를 기다릴 수는 없다.

await this.$store.dispatch('product/getProducts', 'bestseller');

이 함수는 데이터를 반환하거나 새 작업을 호출합니다.

getProducts({commit}, type) {
    axios.get(`/api/products/${type}`)
        .then(res => {
            let products = res.data;
            commit('SET_PRODUCTS', {products, type})
        }).catch(err => {
        console.log(err);
    })
},

그리고 이 함수는 비동기 함수로 인해 약속을 반환합니다.

async function return promise

async getProducts({commit}, type) {
    let res = await axios.get(`/api/products/${type}`);

    commit('SET_PRODUCTS', {products: res.data, type});

}

이제 위의 기능을 사용하여

await this.$store.dispatch('product/getProducts', 'bestseller');

wait 키워드와 함께 또는 공리도 약속을 반환하기 때문에 공리도 반환할 수 있습니다.

언급URL : https://stackoverflow.com/questions/55700815/async-await-with-vuex-dispatch

반응형