Promise.prototype.finally()
Promise.prototype.finally() 方法返回一個Promise,在promise執行結束時,無論結果是fulfilled或者是rejected,在執行then()和catch()後,都會執行finally指定的回調函數。這爲指定執行完promise後,無論結果是fulfilled還是rejected都需要執行的代碼提供了一種方式,避免同樣的語句需要在then()和catch()中各寫一次的情況。
const Gen = (time) => {
return new Promise((resolve, reject) => {
setTimeout(function () {
if (time < 500) {
reject(time)
} else {
resolve(time)
}
}, time)
})
}
Gen(Math.random() * 1000)
.then(val => console.log('resolve', val))
.catch(err => console.log('reject', err))
.finally(() => { // 不管走resolve 還是reject 都要走這裏
console.log('finish')
})