为什么这个承诺没有解决回给呼叫者?

克拉斯·麦克

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

调用代码:

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')
        })
    })
  }
}
鲍勃·范格
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已经创建了一个promise。如果return datathen回调catch函数中添加,然后在回调函数中抛出,以使调用api接收数据/错误。

请注意,承诺会在FETCH_PRODUCTS完成之前解决,为确保操作也已完成,您应编写:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章