【发布时间】:2018-08-01 10:25:22
【问题描述】:
简要说明
我目前正在努力掌握以下实现的结构:
// Method from API Class (layer for communicating with the API)
call() {
// Return axios request BUT handle specific API errors e.g. '401 Unauthorized'
// and prevent subsequent calls to `then` and `catch`
}
// Method from Form Class (used for all forms)
submit() {
// Call the `call` method on the API class and process
// the response.
// IF any validation errors are returned then
// process these and prevent subsequent calls to `then`
// and `catch`
}
// Method on the component itself (unique for each form)
onSubmit() {
// Call the `submit` method on the Form class
// Process the response
// Handle any errors that are not handled by the parent
// methods
}
我是这样实现的:
// Method from API Class (layer for communicating with the API)
call() {
// The purpose of this is to execute the API request and return
// the promise to the caller. However, we need to catch specific
// API errors such as '401 Unauthorized' and prevent any subsequent
// `then` and `catch` calls from the caller
return new Promise((resolve, reject) => {
this.axios.request(request)
.then(response => {
resolve(response); // Do I actually need to do this?
})
.catch(error => {
// Here we need to handle unauthorized errors and prevent any more execution...
reject(error);
});
});
}
// Method from Form Class (used for all forms)
submit() {
// The purpose of this is to call the API, and then, if it
// returns data, or validation errors, process these.
return new Promise((resolve, reject) => {
api.call()
.then(response => {
// Process form on success
this.onSuccess(response.data);
resolve(response.data);
})
.catch(error => {
// Process any validation errors AND prevent
// any further calls to `then` and `catch` from
// the caller (the form component)
this.onFail(error.response.data.error.meta);
reject(error);
})
.then(() => this.processing = false); // This MUST run
});
}
// Method on the component itself (unique for each form)
onSubmit() {
this.form.submit()
.then(response => {
// This should only run if no errors were caught in
// either of the parent calls
// Then, do some cool stuff...
});
}
问题
我的 cmets 应该解释我想要达到的目标,但要清楚:
- 如何捕获某些错误,然后防止从调用类/组件运行对
then和catch的任何进一步调用? - 真的有必要每次返回一个
new Promise吗? - 我知道
axios.request已经返回Promise,但我不知道如何访问resolve和reject方法而不用新的Promise包装它。如有错误,欢迎指正...
【问题讨论】:
-
避免使用promise anti-pattern。你可以做
return this.axios.request(request).catch(...)。 -
@jfriend00 这就是我问这个问题的原因之一,我讨厌我上面的代码,我知道这很糟糕,但我不知道解决方案是什么.你能开导我吗?
-
"和防止后续调用
then和catch" 是什么意思?您的函数正在返回承诺。根据定义,then和catch处理程序将运行。 -
@jfriend00 这就是我之前尝试做的事情,但后来我遇到了从调用类调用
catch和then的问题。有没有办法终止承诺? -
嗯,你的一堆问题没有意义,这就是我没有尝试回答的原因。正如 TJ 所说,如果你返回一个承诺,你不会阻止
.then()和.catch()处理程序运行。相反,您训练调用代码执行什么操作以及跳过什么,并确保您设置了一个已解决的值或拒绝导致调用者做正确事情的原因。
标签: javascript ecmascript-6 promise es6-promise