You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
newPromise((resolve,reject)=>{setTimeout(()=>resolve("result"),2000)}).then(result=>console.log(result)).finally(()=>console.log("Promise end"))// result// Promise end
reject :
newPromise((resolve,reject)=>{thrownewError("error")}).catch(err=>console.log(err)).finally(()=>console.log("Promise end"))// Error: error// Promise end
注意:
finally 没有参数
finally 会将结果和 error 传递
newPromise((resolve,reject)=>{setTimeout(()=>resolve("result"),2000)}).finally(()=>console.log("Promise ready")).then(result=>console.log(result))// Promise ready// result
Promise.prototype.finally()
的作用Promise.prototype.finally()
是 ES2018 新增的特性,它回一个Promise
,在promise
结束时,无论Promise
运行成功还是失败,都会运行finally
,类似于我们常用的try {...} catch {...} finally {...}
Promise.prototype.finally()
避免了同样的语句需要在then()
和catch()
中各写一次的情况reject
:注意:
finally
没有参数finally
会将结果和 error 传递手写一个
Promise.prototype.finally()
不管
Promise
对象最后状态如何,都会执行的操作The text was updated successfully, but these errors were encountered: