javascript - 多个带有返回值的嵌套 axios 调用
问题描述
我正在使用 Vue 并进行多次调用,axios
我只是好奇是否有不同的方法。我的代码正在运行,但我不喜欢它的结构方式,我很想就此获得一些意见。
我觉得这太混乱了,可能应该有更好的方法来做到这一点:
login: function() {
this.toggleLoading();
this.findUser().then(success => {
if(success) {
this.validateSomething().then(success => {
if(success) {
this.auth();
}
});
}
});
}
findUser
并且validateSomething
结构如下:
findUser: function() {
return axios
.post('/find-user', {
id: this.id
})
.then(response => {
if(response.data.success) {
return true;
} else {
this.addErrors(response.data.message);
this.toggleLoading();
return false;
}
})
.catch(this.catchAll)
},
我不想合并findUser
andvalidateSomething
函数,因为我希望能够单独使用它们。
但基本上,我试图实现这样的目标:
login: function() {
this.toggleLoading();
if(!this.findUser()) {
return false;
}
if(this.validateSomething()) {
this.auth();
}
}
这种情况下的最佳实践是什么?
解决方案
你可以使用 async/await,但如果你对 Promise 没问题,你可以清理它
而不是像这样嵌套承诺:
login: function() {
this.toggleLoading();
this.findUser().then(success => {
if(success) {
this.validateSomething().then(success => {
if(success) {
this.auth();
}
});
}
});
}
你可以像这样链接它们:
login: function() {
this.toggleLoading();
this.findUser()
.then(success => {
if (success) {
// returning a promise will allow you to chain the next then below
return this.validateSomething();
}
// if success is not truthy, throw error, which will be caught by catch at end and skip other promise execution
throw new Error('unsuccessful login')
})
.then(success => {
if (success) {
return this.auth();
}
throw new Error('some other reason that it failed')
})
.then(success=>{
return success
})
.catch(err=> handle(err)) // then handle the error
}
TL;博士;
Promise(没有 async/await)很好,问题是您像回调一样实现它们,而不是使用.then
可以轻松解决的预期方式。
推荐阅读
- javascript - 实例函数?一种确定函数是否已在库内创建的方法
- enums - 如何通过 mono cecil 修改枚举类型
- rust - 如何从期货 0.1 组合方法链中提前返回?
- android - Android Edittext 不能专注于 API 22(代码在 API 23 及更高版本上运行良好)
- javascript - 在fusionauth中创建主题时出错
- vue.js - 我只能将 v-model 与 Vue.js 同步吗?
- android - Android Studio 在红线中抱怨“无法访问 androidx.activity.ComponentActivity”,但编译正常
- indexing - Excel 计算 - 复制时的位数
- entity-framework - Entity Framework AddOrUpdate 执行时如何从更新中省略一列或多列?
- php - GuzzleHTTP 客户端 base_uri 与传入的内容不正确