工作之余网上瞄一瞄,无意之中给我瞄到了ES2018 finally()这玩意儿,不禁感慨,又是我孤陋寡闻了,其实这东西已经有一段时间了,只是以前学习promise走马观花也没当回事儿,最重要的可能也是这个东西是很容易被替代的,所以平时也没这个迫切的场景需求促使我发掘它,但如果你有了解,那么接下来你可能在以后工作中能更优雅的处理接下来的问题。
需求思考
在promise执行完后无论是成功又或者失败,我想执行某个方法,那么怎么做?例如实际开发场景:在做移动app开发的时候,需要每次发送请求,都会有‘菊花’提示,请求发送完毕,就需要关闭loading提示框,否则界面就无法被点击。但是请求有的是成功、失败、超时,为了不影响整个系统的正常使用,就需要在请求结束后强制关闭提示框。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| promise
.finally(() => {
// 语句
});
// 等同于
promise
.then(
result => {
// 语句
return result;
},
error => {
// 语句
throw error;
}
); |
上面代码中,如果不使用finally方法,同样的语句需要为成功和失败两种情况各写一次。有了finally方法,则只需要写一次。
针对finally我们如何理解它?通俗来讲就是finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作,它没有可接收的参数,如下代码,在promise最终任何结果下finally都会执行。
1 2 3 4 5 6 7 8 9 10 11 12 13
| new Promise(function (resolve) {
resolve('成功')
})
.then(result => {
console.log(result)
resolve()
})
.catch(error => {
console.log(error)
})
.finally(() => {
console.log('任何')
}); |
如何实现finally
当然,如果你目前直接在客户端去使用这个东西还是不行的,其实自己可以很容易去实现这个方法,如下:
1 2 3 4 5 6 7
| Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
);
}; |
完整demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise-finally</title>
</head>
<body>
</body>
<script>
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
);
};
new Promise(function (resolve) {
resolve('成功')
})
.then(result => {
console.log(result)
resolve()
})
.catch(error => {
console.log(error)
})
.finally(() => {
console.log('任何')
});
</script>
</html> |
「梦想一旦被付诸行动,就会变得神圣,如果觉得我的文章对您有用,请帮助本站成长」
共 0 条评论关于"ES2018 新特性Promise.finally()是个啥你有了解吗?"
最新评论