Promise.prototype.finally()
的作用
Promise.prototype.finally()
是 ES2018 新增的特性,它回一个 Promise
,在 promise
结束时,无论 Promise
运行成功还是失败,都会运行 finally
,类似于我们常用的 try {...} catch {...} finally {...}
Promise.prototype.finally()
避免了同样的语句需要在 then()
和 catch()
中各写一次的情况
new Promise((resolve, reject) => {
setTimeout(() => resolve("result"), 2000)
})
.then(result => console.log(result))
.finally(() => console.log("Promise end"))
// result
// Promise end
reject
:
new Promise((resolve, reject) => {
throw new Error("error")
})
.catch(err => console.log(err))
.finally(() => console.log("Promise end"))
/