首页 > 解决方案 > 为什么这个承诺没有返回给调用者?

问题描述

我有一个与 Vuex 和 Axios 一起运行的 Vue-App。在这个应用程序中,我有处理 API 调用的 vuex-store,但问题是当我调用存储操作时,我无法在调用者中链接响应。任何想法我做错了什么?

调用代码:

import { FETCH_PRODUCTS, ADD_PRODUCT } from './actions.type'

methods: {
    sendNewProduct () {
      this.$store
        .dispatch(ADD_PRODUCT, this.newProductForm)
        .then(() => {
          console.log('This never gets called')
        })
    }
  }

Vuex商店:

const actions = {
  [ADD_PRODUCT] (context, credentials) {
    return new Promise((resolve) => {
      ApiService
        .post('/Products/', {
          Name: credentials.Name,
          Description: credentials.Description,
          Price: credentials.Price
        })
        .then(({ data }) => {
          this.$store
            .dispatch(FETCH_PRODUCTS)
            resolve(data)
        })
        .catch(({ response }) => {
          console.log(response)
          context.commit(SET_ERROR, 'Error adding product')
        })
    })
  }
}

标签: javascriptvue.jsvuejs2axiosvuex

解决方案


const actions = {
  [ADD_PRODUCT](context, credentials) {
    return ApiService.post("/Products/", {
      Name: credentials.Name,
      Description: credentials.Description,
      Price: credentials.Price
    })
      .then(({ data }) => {
        this.$store.dispatch(FETCH_PRODUCTS);
        return data;
      })
      .catch(({ response }) => {
        console.log(response);
        context.commit(SET_ERROR, "Error adding product");
        throw new Error("Error adding product");
      });
  }
};

我已经删除了,new Promise(...)因为 axios 已经创建了一个承诺。如果在回调中添加一个return data并在then回调中添加一个 throwcatch以让调用 api 接收数据/错误。

请注意,承诺在 FETCH_PRODUCTS 完成之前解析,以确保该操作也完成,您可以编写:

.then(({ data }) => {
  return this.$store.dispatch(FETCH_PRODUCTS)
    .then(() => data);
})

推荐阅读