当前位置: 首页 > 科技观察

Promise.prototype.finally的作用,如何实现Promise.prototype.finally

时间:2023-03-17 11:04:42 科技观察

本文转载自微信公众号《三分钟学会前端》,作者安姐。转载本文请联系三分钟学习前端公众号.Promise.prototype.finally()的作用Promise.prototype.finally()是ES2018的新特性。它返回一个承诺。当promise结束时,无论Promise运行成功还是失败,都会运行finally,类似于我们常用的try{...}catch{...}finally{...}Promise.prototype.finally()避免了需要在then()和catch()中分别写一次相同语句的情况newPromise((resolve,reject)=>{setTimeout(()=>resolve("result"),2000)}).then(result=>console.log(result)).finally(()=>console.log("Promiseend"))//result//Promiseendreject:newPromise((resolve,reject)=>{thrownewError("error")}).catch(err=>console.log(err)).finally(()=>console.log("Promiseend"))//Error:error//Promiseend注意:finally没有参数,finally会传递结果和错误newPromise((resolve,reject)=>{setTimeout(()=>resolve("result"),2000)}).finally(()=>console.log("Promiseready")).then(result=>console.log(result))//Promiseready//result写一个Promise.prototype.finally()不管Promise对象的最终状态如何,都会执行MyProm操作ise.prototype.finally=乐趣动作(cb){returnthis.then(函数(值){returnMyPromise.resolve(cb()).then(function(){returnvalue})},函数(err){returnMyPromise.resolve(cb()).then(function(){throwerr})})}来自:https://github.com/sisterAn/blog