【ES9(2018)】Promise.prototype.finally()
生活随笔
收集整理的這篇文章主要介紹了
【ES9(2018)】Promise.prototype.finally()
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
指定不管最后狀態(tài)如何都會執(zhí)行的回調(diào)函數(shù)。
Promise.prototype.finally() 方法返回一個(gè)Promise,在promise執(zhí)行結(jié)束時(shí),無論結(jié)果是fulfilled或者是rejected,在執(zhí)行then()和catch()后,都會執(zhí)行finally指定的回調(diào)函數(shù)。這為指定執(zhí)行完promise后,無論結(jié)果是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 關(guān)閉
需要每次發(fā)送請求,都會有l(wèi)oading提示,請求發(fā)送完畢,就需要關(guān)閉loading提示框,不然界面就無法被點(diǎn)擊。不管請求成功或是失敗,這個(gè)loading都需要關(guān)閉掉,這時(shí)把關(guān)閉loading的代碼寫在finally里再合適不過了。
場景2:數(shù)據(jù)庫斷開連接
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()})總結(jié)
以上是生活随笔為你收集整理的【ES9(2018)】Promise.prototype.finally()的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux学习之打印进程树
- 下一篇: 机器人炒饭小块头一一_一罐好饭,智能机器