javascript - 当 ajax 调用在 axios 中成功时做一些事情 - 在 axios 中链接 then()
问题描述
当 ajax 调用在 axios 中成功时,我正在尝试做某事
save() {
this.isUpdateTask ? this.updateProduct() : this.storeProduct()
this.endTask()
}
如果更新或存储产品的 ajax 调用成功,我想运行 endTask() 函数。
我不希望在 ajax 调用不成功时运行 endTask() 函数。
我怎样才能做到这一点?
商店功能:
storeProduct() {
return axios
.post("products", this.getFormData())
.then(
response => this.products.push(response.data.data)
)
.catch(
error => (this.serverErrors = error.response.data.errors.detail)
)
},
解决方案
您可以在新的 Promise 中调用此方法,如下例所示:
save() {
Promise.resolve()
.then(() => {
return this.isUpdateTask ? this.updateProduct() : this.storeProduct()
})
.then(() => {
this.endTask()
})
}
还有其他方法可以做:
save() {
(this.isUpdateTask ? this.updateProduct() : this.storeProduct()).then(() => {
this.endTask()
})
}
或分配给一个变量:
save() {
const promiseUpdate = this.isUpdateTask ? this.updateProduct() : this.storeProduct()
promiseUpdate.then(() => {
this.endTask()
})
}
或者使用异步/等待:
async save() {
await this.isUpdateTask ? this.updateProduct() : this.storeProduct()
// this code runs only if everything happen successful
await this.endTask()
}
关于endTask
执行直到响应不成功,是因为您对待error
storProduct 内部。
.catch(
error => (this.serverErrors = error.response.data.errors.detail)
)
因此,在这种情况下,有必要再次重新抛出错误:
.catch(
error => {
this.serverErrors = error.response.data.errors.detail
throw error
}
)
Promise的catch
作用与try/catch
from javascript 相同。
在这里有更多关于catch
承诺的参考。
推荐阅读
- talend - 是否可以使用 TOS for Big Data 从共享路径访问源 excel 文档
- sql - Oracle 10g aggregating from two different rows and columns into a single row
- php - 我想使用 php 中的函数打印特定数量的用户选择的数学表
- ipfs - 错误:ipfs 配置文件已存在
- python - 可以将 OpenMP 与 python 的 concurrent.futures.ThreadPoolExecutor 混合使用吗?
- python - 我可以在 python2/3 中同时使用多种不同方法的多处理吗
- javascript - 仅验证一个字段 ng-required angularjs
- php - Symfony 3.4 中的 Doctrine 2.2 日期时间字符串转换
- c - 如何让 valgrind 报告“绝对丢失”发生的“位置”
- haskell - 使用 GADT 的类似仆人的实现