javascript - 为什么这个承诺没有返回给调用者?
问题描述
我有一个与 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')
})
})
}
}
解决方案
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);
})
推荐阅读
- javascript - 使用 javaScript 基于 flex wrap 属性设置 div 样式
- javascript - 在 Datatables PHP 中匹配文本和 img
- python - 确保指令中的字符串正是您返回的内容
- c - python 的 help() 和 dir() 函数的 C 等价物是什么?
- html - 如何对齐跨度旁边的中心文本?
- python - 当列表不包含 if 语句指定的条件时,为什么会触发这个 if 语句?
- python - 我想对文件夹中的所有图像进行扩充。目前我只有一个的代码。我怎样才能一次做同样的事情?
- php - 如何获取for循环的最后一项
- sql - 为什么 ORDER 本身会改变分析函数中的结果?
- css - Index.html 路径无法隐藏