Promise.finally()介绍
Promise.finally()是ES2018新增的API,它的作用是在Promise完成或拒绝后都会执行,不管Promise最终状态如何,它接收一个普通函数,不返回任何值。
Promise.finally()使用方法
Promise.finally()接收一个函数作为参数,该函数不接收任何参数,也不返回任何值,它会在Promise完成或拒绝后都会执行。
Promise.resolve('success') .then(result => { console.log(result); }) .catch(error => { console.log(error); }) .finally(() => { console.log('finally'); }); // success // finally
以上代码中,Promise.resolve()返回一个Promise对象,它的状态为resolved,会执行then()方法,执行finally()方法,输出finally。
Promise.finally()用处
Promise.finally()可以用来做一些清理工作,比如:
- 关闭加载动画
- 取消网络请求
- 清除定时器
- 清除监听事件
这些清理工作不管Promise最终状态如何都会执行,可以放到finally()方法中。
// 关闭加载动画 Promise.resolve() .then(result => { console.log(result); }) .catch(error => { console.log(error); }) .finally(() => { console.log('close loading animation'); });