如何在ES8的async/await语法中使用Promise.prototype.finally()?
在Async/Await中使用Finally的正确方式
嘿,这个问题问得好!其实在async/await语法里,对应Promise链式调用中.finally()的就是try/finally代码块——它和你已经在用的try/catch是完美搭档,不管异步操作成功还是失败,finally里的代码都会执行,和.finally()的作用完全一致。
直接上代码示例
我们把你原来的async函数改造一下,加上finally逻辑:
async () => { try { const result1 = await firstAsynchronousFunction(); const result2 = await secondAsynchronousFunction(result1); console.log(result2); } catch(err) { throw new Error(`Something failed: ${err.message}`); } finally { // 不管try里的代码成功还是catch捕获到错误,这里的代码都会执行 console.log(`All Tasks are Done`); } }
和Promise链式调用的对比
你之前写的Promise链式代码:
new Promise((resolve) => { console.log(`Initial`); resolve(); }) .then(() => { console.log(`Task Number One`); }) .catch(() => { console.log(`Task in Error`); }) .finally(() => { console.log(`All Tasks is Done`); })
用async/await改写后,逻辑完全等价:
async () => { try { console.log(`Initial`); await new Promise(resolve => resolve()); console.log(`Task Number One`); } catch(err) { console.log(`Task in Error`); } finally { console.log(`All Tasks are Done`); } }
关键要点
finally块的代码一定会执行,不管try里的await操作是成功resolved还是失败rejected(被catch捕获)- 你可以在finally里做一些清理工作,比如关闭数据库连接、清除加载状态这类不管结果如何都要做的操作
- 如果在catch里重新抛出错误,finally仍然会执行,之后错误才会继续向上传递
内容的提问来源于stack exchange,提问作者AmerllicA
相关产品推荐
相关产品推荐

