Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the function of Promise.prototype.finally?

Shulou Source: shulou.com Published: 2022-06-03 06:40:50 10月02日 Update

This article mainly explains "what is the role of Promise.prototype.finally". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the role of Promise.prototype.finally".

The role of Promise.prototype.finally ()

Promise.prototype.finally () is a new feature of ES2018. It returns a Promise. At the end of promise, regardless of whether the Promise runs successfully or not, it will run finally, similar to our commonly used try {.} catch {.} finally {.}

Promise.prototype.finally () avoids the need to write the same statement once in then () and 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") / / Error: error / / Promise end

Note:

Finally has no parameters

Finally will pass the result to error.

New Promise ((resolve, reject) = > {setTimeout (() = > resolve ("result"), 2000)}) .finally (() = > console.log ("Promise ready")) .then (result = > console.log (result)) / / Promise ready / / result handwritten a Promise.prototype.finally ()

Actions that are performed regardless of the final state of the Promise object

MyPromise.prototype.finally = function (cb) {return this.then (function (value) {return MyPromise.resolve (cb ()) .then (function () {return value})}, function (err) {return MyPromise.resolve (cb ()). Then (function () {throw err})})} Thank you for reading. That's what Promise.prototype.finally does. After the study of this article, I believe that we have a deeper understanding of what the role of Promise.prototype.finally is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Function learning content situation run success parameters objects that is commonly used ideas articles more characteristics states knowledge knowledge points articles results sentences Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Information MySQL Shulou Tech Info OPPO Reno