javascript - 在给定方法内的所有承诺解决后执行方法
问题描述
在 Vue.js 组件中,我有一些使用axios调用 API 的方法。
在不同的情况下,我需要在此方法中的调用解决后执行一些代码,但我不想在链接中添加一堆if
语句.then()
到 axios 调用中。
methods: {
callApi() {
axios.get('/api')
.then(() => {
// call has resolved, request is done
})
},
firstMethod() {
this.callApi()
// Need to wait for the call to resolve
// Do something
},
secondMethod() {
this.callApi()
// Need to wait for the call to resolve
// Do something else
}
}
如您所见,一旦请求完成firstMethod
,secondMethod
两者都依赖callApi
但应该做不同的事情。我更喜欢将这个逻辑拆分到不同的函数中,而不是在callApi
方法中使用条件。有没有办法做到这一点而不必在里面添加这个逻辑
callApi
?
解决方案
已callApi
返回承诺链,然后在firstMethod
and中使用并返回它secondMethod
。
methods: {
callApi() {
return axios.get('/api')
.then(() => {
// call has resolved, request is done
})
},
firstMethod() {
return this.callApi()
.then(() => {
// Need to wait for the call to resolve
// Do something
})
},
secondMethod() {
return this.callApi()
.then(() => {
// Need to wait for the call to resolve
// Do something else
})
}
}
无论调用callApi
,firstMethod
还是secondMethod
应该检查失败并处理/报告它。
您的原始代码违反了承诺规则之一:该函数应始终返回链或处理拒绝。(是的,那是或[99.9% 的时间],不是和。)
推荐阅读
- image - Flutter:从新网络保存和加载图像
- android - Android edittext软键盘在edittext外部单击时消失
- c# - 如何通过 Discord Bot 重命名用户
- python - 如何更改 seaborn barplot 的大小?
- flutter - 颤动:BehaviorSubject 不重建小部件
- python - 我怎么知道我是否有 Python?
- php - 将 oCompany 保存在 cookie 或会话中
- azure - 无法访问 EF Core 中生成的 SQL
- gitlab - 使用没有访问令牌的 GitLab REST API
- sql - 改进项目所需的指导