【ES9(2018)】Promise.prototype.finally()
生活随笔
收集整理的這篇文章主要介紹了
【ES9(2018)】Promise.prototype.finally()
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
指定不管最后狀態(tài)如何都會執(zhí)行的回調函數。
Promise.prototype.finally() 方法返回一個Promise,在promise執(zhí)行結束時,無論結果是fulfilled或者是rejected,在執(zhí)行then()和catch()后,都會執(zhí)行finally指定的回調函數。這為指定執(zhí)行完promise后,無論結果是fulfilled還是rejected都需要執(zhí)行的代碼提供了一種方式,避免同樣的語句需要在then()和catch()中各寫一次的情況。
new Promise((resolve, reject) => {setTimeout(() => {resolve('success')}, 1000) }).then(res => {console.log(res) }).catch(err => {console.log(err) }).finally(() => {console.log('finally') })場景1:loading 關閉
需要每次發(fā)送請求,都會有l(wèi)oading提示,請求發(fā)送完畢,就需要關閉loading提示框,不然界面就無法被點擊。不管請求成功或是失敗,這個loading都需要關閉掉,這時把關閉loading的代碼寫在finally里再合適不過了。
場景2:數據庫斷開連接
let connection db.open().then(conn => {connection = connreturn connection.select({name: 'Jane'})}).then(result => {// Process result// Use `connection` to make more queries})···.catch(error => {// handle errors}).finally(() => {connection.close()})總結
以上是生活随笔為你收集整理的【ES9(2018)】Promise.prototype.finally()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux学习之打印进程树
- 下一篇: 机器人炒饭小块头一一_一罐好饭,智能机器