我是编程新手,正在尝试学习最佳实践。我继续遇到的一个问题是重复的说明,如下面的代码示例所示。如您所见,我this.spinner = false
声明了不少于三遍。当然,有更好的方法吗?
.then((response) => {
console.log(response.data);
if (response.data.error == true) {
this.error = true;
this.buttonTxt = "get BOM";
this.spinner = false;
this.message = response.data.message;
} else {
this.buttonTxt = "get BOM";
this.spinner = false;
this.bomData = response.data.bomData;
}
})
.catch((response) => {
console.log(response);
this.error = true;
this.spinner = false;
this.message = "Network or server error. Could next execute PHP.";
this.buttonTxt = "get BOM";
});
答案 0 :(得分:4)
Promise有一个.finally()
子句,无论已解决或被拒绝的诺言都将运行。您可以在所有情况下一次在其中写入this.spinner = false;
。有关更多信息,请检查here
例如
.then(() => {/* do whatever upon success */})
.catch( () => {/* error */})
.finally( () => this.spinner = false );
答案 1 :(得分:0)
.then((response) => {
console.log(response.data);
// common code
this.buttonTxt = "get BOM";
this.spinner = false;
if (response.data.error == true) {
this.error = true;
this.message = response.data.message;
} else {
this.bomData = response.data.bomData;
}
})
.catch((response) => {
console.log(response);
this.error = true;
this.spinner = false;
this.message = "Network or server error. Could next execute PHP.";
this.buttonTxt = "get BOM";
});
答案 2 :(得分:0)
在成功或失败的情况下,您都设置了spinner和btnTxt。
apply
答案 3 :(得分:0)
由于您始终将微调器设置为false
,因此您可以简单地使用该值开始对其进行初始化。因此您的代码将如下所示:
// define this before chaining on .then
this.spinner = false;
// continue with your code here
.then((response) => {
console.log(response.data);
if (response.data.error == true) {
this.error = true;
this.buttonTxt = "get BOM";
this.message = response.data.message;
} else {
this.buttonTxt = "get BOM";
this.bomData = response.data.bomData;
}
})
.catch((response) => {
console.log(response);
this.error = true;
this.message = "Network or server error. Could next execute PHP.";
this.buttonTxt = "get BOM";
});
现在,您只需在需要时将其设置为true
。
更好的是,您可以编写将相关操作分组在一起的函数。例如,我看到您总是同时拥有this.error = true
和this.buttonTxt = "get BOM"
和动态this.message
变量。所以你可以这样写一个函数:
function handleError(message) {
this.error = true;
this.buttonText = "get BOM";
this.message = message;
}
并直接传递错误消息。
因此,将所有更改汇总在一起,您的代码将如下所示:
// define these before chaining on .then
this.spinner = false;
this.handleError = function handleError(message) {
this.error = true;
this.buttonText = "get BOM";
this.message = message;
}
// continue with your code here
.then((response) => {
console.log(response.data);
if (response.data.error == true) {
this.handleError(response.data.message)
} else {
this.buttonTxt = "get BOM";
this.bomData = response.data.bomData;
}
})
.catch((response) => {
console.log(response);
this.handleError("Network or server error. Could next execute PHP.");
});