finally的作用
Promise对象的finally()方法用于在Promise成功或拒绝时使用
不管promise最后的状态,在执行完then或catch指定的回调函数以后,都会执行finally方法指定的回调函数,它可以防止Promise的then()和catch()方法中的代码重复。
let promise = new Promise((resolve,reject) => {
resolve('resolve')
})
promise.then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
}).finally(()=> {
console.log('this finally')
})
// resolve
// this finally
finally的使用
平常在工作中经常会遇到一些加载loading的需求,一般都在请求前设置loading展示,请求完成后关闭loading,刚开始我下意识把关闭loading放到then方法里面去处理,发现如果请求出现错误的情况,页面loading是还在的,就需要在catch方法里重写一遍导致代码重复,后面才了解到finally方法可以处理Promise的then和catch方法中代码重复的功能。
this.opLoading = true;
api.then((res) => {
if(res.code == 200){
// xxx
}
}).catch((err) => {
// xxx
}).finally(()=> {
this.opLoading = false;
})
到这里就结束了,如果这篇文章对您有所帮助,可以点赞加收藏👍