Promise.prototype.finally的新功能特性


Promise.prototype.finally() 是 ES2018 新增的特性,它回一个 Promise ,在 promise 结束时,无论 Promise 运行成功还是失败,都会运行 finally ,类似于我们常用的 try {…} catch {…} finally {…}

Promise.prototype.finally() 避免了同样的语句需要在 then() 和 catch() 中各写一次的情况


  1. new Promise((resolve, reject) => { 
  2.   setTimeout(() => resolve("result"), 2000) 
  3. }) 
  4.   .then(result => console.log(result)) 
  5.   .finally(() => console.log("Promise end")) 
  6.  
  7. // result 
  8. // Promise end 

reject :


  1. new Promise((resolve, reject) => { 
  2.   throw new Error("error"
  3. }) 
  4.   .catch(err => console.log(err)) 
  5.   .finally(() => console.log("Promise end")) 
  6.  
  7. // Error: error 
  8. // Promise end 

注意:

  • finally 没有参数
  • finally 会将结果和 error 传递

  1. new Promise((resolve, reject) => { 
  2.   setTimeout(() => resolve("result"), 2000) 
  3. }) 
  4.   .finally(() => console.log("Promise ready")) 
  5.   .then(result => console.log(result)) 
  6.  
  7. // Promise ready 
  8. // result 

手写一个 Promise.prototype.finally()

不管 Promise 对象最后状态如何,都会执行的操作


  1. MyPromise.prototype.finally = function (cb) { 
  2.   return this.then(function (value) { 
  3.     return MyPromise.resolve(cb()).then(function () { 
  4.       return value 
  5.     }) 
  6.   }, function (err) { 
  7.     return MyPromise.resolve(cb()).then(function () { 
  8.       throw err 
  9.     }) 
  10.   }) 
【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章