Because a few days ago did a promise object to catch the wrong interview topic, so these days again revisit the Promise object. Now take this question to share some very basic knowledge points.
Here is an interview topic, three examples of promise object capture errors, and what is the difference between the returned results.
// add Error event using throw var p = new Promise (function (resolve, reject) {resolve ( "OK" ); throw new Error (' Error0 ' ); // settimeout (function () {throw new Error (' Error1 ')}, 0); function (value) {Console.log (value)}). catch (Funcrion (err) {Console.log (Err)})
process.on ( ' unhandledrejection ', function (err, p) {console.error ( ' catch exception: '
// setting timers to throw error events var New Promise (function(resolve, reject) { resolve ("OK"); // throw new Error (' error0 '); SetTimeout (functionthrownew Error (' Error1 ')}, 0);});
P.then (function (value) {
}). catch (Funcrion (err) { console.log (err) });
process.on ( ' unhandledrejection ', function (err, p) {console.error ( ' catch exception: '
// add error events at the same time var p = function (resolve, reject) {resolve ( "OK" ); throw new Error (' Error0 ' ); SetTimeout ( function () {throw Span style= "color: #0000ff;" >new Error (' Error1 ')}, 0 function (value) {Console.log ( Value)}). catch (Funcrion (err) {Console.log (Err)}) ;
Process.on (function (err, p) {console.error (' catch exception: ', Err.stack)});
First put the problem here, if one can see the results of the big guys will not have to read down.
About four ways of implementing asynchronous programming in JavaScript have been known a long while ago. 1. callback function 2. Event Listener 3. Publish, subscribe to event 4.promise objects
The first three kinds we can say is not uncommon, callback function, event monitoring This is the "soul" JS. Publishing, subscribing to events is also more common. Today we will be able to learn the promise object, and it can implement the principle of asynchronous programming, and finally the answer to the above topic and some of my personal understanding.
What is a promise object, what can it do?
The promises object is a specification presented in the COMMONJS workgroup to provide a unified interface for asynchronous programming. is now implemented in ECMAScript2015 (ES6).
Promise
The object is used for deferred (deferred) and asynchronous (asynchronous) computations: A Promise object represents an operation that has not yet been completed but is expected to be completed in the future.
Promise
An object is a proxy that returns a value that may not be known when the Promise object is created. It allows you to specify the processing method for the success or failure of an asynchronous operation. This allows the Async method to return a value like a synchronous method: The Async method returns a Promise object that contains the original return value instead of the original return value.
Promise
Objects have the following states:
Pending: Represents an initial state, non-fulfilled or rejected.
fulfilled: successful operation.
rejected: failed operation.
Each asynchronous task returns a Promise object that has a then method that allows you to specify a callback function. The corresponding callback function can be executed according to the state of the Promise object. We probably know the meaning of the existence of promise, and let's take a look at some of the APIs commonly used by this object.
Second, the common API
1.promise.prototype.then ()
The promise instance has the then method, so then the then method is defined on the prototype object Promise.prototype. Its purpose is to add a callback function to the promise instance when the state changes.
The first parameter of the then () method is the callback function for the resolved state, and the second parameter (optional) is the callback function for the rejected state. The then method returns a new promise instance, not the original promise instance, so it can be chained and then a then method can be called afterwards.
var p=New Promise (function(resolve,eject) { Resolve ("OK"); }); P.then (functionfunction(ERR) (Console.log (Err )));
The second parameter of the then method is generally not recommended for writing. There are two reasons: the first reason, because it is a chain operation, the then method may have other operations, if the error-trapping function at this point in front of the next method, and then no error capture method, then the error will not be captured. The second reason is that in the then method, two parameters are written in a large number of callback functions, so the structure looks rather confusing.
So here is the method, generally written in the end of the chain-style notation. This allows all previous errors to be captured.
2.promise.prototype.catch ()
This method is the. then (Null,rejection) alias, which also shows that this method is specifically designed to capture only error messages, specifying the callback function when an error occurs.
But there are a few things to note when using this method:
(1) When the promise State has become resolved, it is invalid to throw an error again. Look at the code below.
var promise=New Promise (function(resolve,reject) { Resolve ("OK"); Throw New Error ("test"); }); Promise.then (function(value) {Consloe.log (val);}) . Catch (function(error) {Console.log (ERR)});
The Promise State is resolve ("OK"), then the promise status is changed to Resolved, and then the throw error does not change the promise state to rejected, so the catch method does not catch the error.
There are only two possible changes to the state of the Promise object: from Pending to resolved and from Pending to rejected. As long as any of these two situations occur, the state is equivalent to solidification, and will not change, will keep this result.
(2) Try to write the catch method at the end of the chain operation, the reason has already said, also is the catch error is not recommended to write then method of one of the reasons. The error will always bubble to the end, and the catch will catch all errors at the end. Errors that occur after the catch are not captured when the catch is set prematurely, and then there is no catch method.
(3) When there is no callback function that uses the Catch method to specify the error handler, the error thrown inside the Promise object is not passed to the outer code.
3.promise.resolve ()
The purpose of this approach is to convert existing objects into promise objects, which can then be executed.
Promise.resolve ("foo"); // This is the equivalent of the following notation New Promise (function(resolve) { resolve ("foo"); });
4.promise.all ()
This method is used to wrap multiple promise instances into a new promise instance.
var p=promise.all ([p1,p2,p3]);
P1,P2,P3 are instances of the Promise object, and if not, the Promise.resolve () method is called and the arguments are converted to promise instances before further processing can proceed.
and pay attention to two points:
(1) The state of P becomes fulfilled only after the P1,P2,P3 state has changed to fulfilled.
(2) As long as any state in the p1.p2,p3 becomes rejected,p, it becomes rejected.
Three, the principle of implementing asynchronous programming
The approximate principle is that, as they say, the Promise object is equivalent to a state machine in which the Resolve method is used internally to make it the fulfilled state when the initial state succeeds or the rejected state after execution fails. At this point, the internal work is completed, and the internal state changes are monitored externally, and the corresponding handler functions are called by the then () method (The catch () method corresponds to the second parameter method inside then). This is probably the principle of asynchronous programming for promise objects.
Iv. answers to the questions given at the beginning
We can see that three instance external functions are written exactly the same way, unlike the method used to throw an error inside an promise object.
The first throws an error using throw, which should be caught by the external catch method. But, but. It has been said that the Promise object state is "solidified" once it has been changed, once it is executed
Resolve ("OK");
After the state is set to fulfilled, the error handling is thrown, and the errors are not captured by subsequent catch methods. So it's only going to execute the contents of the then () method. Only "OK" will be printed.
The second one throws an error through the timer. Although the state has changed to fulfilled, the error thrown by the timer is an asynchronous throw error that cannot be captured by the try catch, so it is not related to the Promise object, so the error can be thrown normally, so the answer here should be to print "OK" first. Then throws the error defined in the process.
The third uses both throw and timer to throw an error. Should it be the same as the second one? That's the wrong thing to think. When a throw is executed, although the error is not handled by an external function capture, this is a real error, and for JavaScript, there is no further execution. So it does not execute until the timer throws an error and stops. So the answer to this question should be to just print out "OK".
Well, the end ... ..... .... ... .... ..... ..... ..... ..... ....., ... and ..... ......., ... and ..... the .....-.......
Talking about the Promise object in JavaScript by a pen question