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')
})

本文深入探讨了Promise.prototype.finally()方法的使用,该方法允许在Promise执行完毕后,无论结果是成功还是失败,都能执行指定的回调函数。通过一个具体的示例,展示了如何在then()和catch()之后统一执行某些操作,避免代码重复。
4068

被折叠的 条评论
为什么被折叠?



