How to use the Promise class of JavaScript
This article mainly introduces the JavaScript Promise class how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this JavaScript Promise class how to use the article will have a harvest, let's take a look.
The Promise class has .then () .catch () and .finally (), whose argument is a function, .catch () adds the function in the argument to the normal execution sequence of the current Promise, .catch () sets the exception handling sequence of the Promise, and .finally () is the sequence that must be executed at the end of the Promise execution. The functions passed in by .then () are executed sequentially, and any exceptions jump directly to the catch sequence:
Case study
New Promise (function (resolve, reject) {
Console.log (1111)
Resolve (2222)
}) .then (function (value) {
Console.log (value)
Return 3333
}) .then (function (value) {
Console.log (value)
Throw "An error"
}) .catch (function (err) {
Console.log (err)
})
Execution result:
1111
2222
3333
An error
You can put an argument in resolve () to pass a value to the next then, or a function in then can return a value to pass to then. However, if a Promise object is returned in the then, then the next then will be equivalent to operating on the returned Promise, as you can see from the timer example just now.
An exception is usually passed to the subsequent catch function in the reject () parameter to handle the exception.
But please note the following two points:
The scope of resolve and reject is only the starting function, excluding then and other sequences.
Resolve and reject don't stop the initiator function, so don't forget return.
This is the end of the article on "how to use the Promise class of JavaScript". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use the Promise class of JavaScript". If you want to learn more, you are welcome to follow the industry information channel.