【译】ES2018 新特性:Promise.prototype.finally()

Jordan Harband 提出了 Promise.prototype.finally 这一章节的提案。html

如何工做?

.finally() 这样用:git

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
复制代码

finally 的回调老是会被执行。做为比较:es6

  • then 的回调只有当 promise 为 fulfilled 时才会被执行。
  • catch 的回调只有当 promise 为 rejected,或者 then 的回调抛出一个异常,或者返回一个 rejected Promise 时,才会被执行。 换句话说,下面的代码段:
promise
.finally(() => {
    «statements»
});
复制代码

等价于:github

promise
.then(
    result => {
        «statements»
        return result;
    },
    error => {
        «statements»
        throw error;
    }
);
复制代码

使用案例

最多见的使用案例相似于同步的 finally 分句:处理完某个资源后作些清理工做。无论有没有报错,这样的工做都是有必要的。 举个例子:npm

let connection;
db.open()
.then(conn => {
    connection = conn;
    return connection.select({ name: 'Jane' });
})
.then(result => {
    // Process result
    // Use `connection` to make more queries
})
···
.catch(error => {
    // handle errors
})
.finally(() => {
    connection.close();
});
复制代码

.finally() 相似于同步代码中的 finally {}

同步代码里,try 语句分为三部分:try 分句,catch 分句和 finally 分句。 对比 Promise:promise

  • try 分句至关于调用一个基于 Promise 的函数或者 .then() 方法
  • catch 分句至关于 Promise 的 .catch() 方法
  • finally 分句至关于提案在 Promise 新引入的 .finally() 方法

然而,finally {} 能够 return 和 throw ,而在.finally() 回调里只能 throw, return 不起任何做用。这是由于这个方法不能区分显式返回和正常结束的回调。bash

可用性

深刻阅读


原文:http://exploringjs.com/es2018-es2019/ch_promise-prototype-finally.htmlasync

相关文章
相关标签/搜索