1、 About promise
Promise is a solution of asynchronous programmingIt is more reasonable and powerful than traditional solutions (callback functions and events). It was first proposed and implemented by the community. ES6 has written it into the language standard, unified the usage, and provided the native languagePromise
Object.
so-calledPromise
In short, it is a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, promise is an object from which messages of asynchronous operations can be obtained. Promise provides a unified API, and all kinds of asynchronous operations can be handled in the same way.
It represents an asynchronous operation. There are three states:
-
pending
In progress: initial state, initial state, incomplete or rejected. -
resolved
(completed): indicates that the operation completed successfully. also calledfulfilled
。 -
rejected
(failed): indicates that the operation failed.
YesPromise
The asynchronous operation can be expressed as the process of synchronous operation, but it also has the following advantagesshortcoming:
- Once created, it is executed immediately and cannot be cancelled halfway.
- If the callback function is not set,
Promise
An internal error is not reflected externally. - When in
Pending
It is impossible to know which stage (just started or about to finish) the current progress has reached.
2、 Application examples
1. Create promise
var promise = new Promise(
/* executor */
function(resolve, reject){
...
}
);
The executor function is implemented immediately by Promise, passing resolve and reject functions. (before invoking the actuator or even returning the object created before the Promise constructor)
Inexecutor
Internally, promise may have the following state changes:
1. Resolve is called, and the promise changes from pending to resolved, which means that the promise is resolved successfully
2.reject
When called, the project changes from pending to rejected, which means that the value of the project cannot be used for subsequent processing, that is, it is rejected
be careful:
- If in
executor
If any exception is thrown during the execution of the method, the project will be rejected immediately (that is, the reject method will be called),executor
The return value of is also ignored.- If a promise object is in
resolved
orrejected
Instead of the pending state, it can also be called thesettled
Status.
2. Handle promise instance
-
then: after the promise instance is generated, you can use the
then
Methods are specified separatelyResolved
Status andReject
The callback function of the state.promise.then(function(value) { //Called when the success state is resolved }, function(error) { //Called when failure state is reject });
then
Method can take two callback functions as parameters.
The first callback function: when the promise state becomesresolved
Is called when. Its parameter is the return value of the resolve method of promise.
The second callback function: when the promise state becomesrejected
Is called when. Its parameter is the return value of the reject method of project. It is an optional parameter.
-
catch:
Promise.prototype.catch
The method is.then(null, rejection)
Alias forSpecifies the callback function when an error occurs。promise.then(function(posts) { // ... }).catch(function(error) { console.log ('error! ', error); // handle the errors that occur when promise and the previous callback function are running });
-
Extension:
-
Promise.prototype.then
AndPromise.prototype.catch
Method, so they can be chained.But the new promise instance generated by the function return value is returned, not the original promise instance。
-
Note:
- The error of the promise object is “bubbling” and is passed back until it is caught. In other words, mistakes are always followed by the next one
catch
Statement capture.
3. Package multiple promise instances into a new promise instance
-
Promise.all(iterable)
: returns “project” when all “projects” in the iteratable parameters have been completed, or the first “project” passed fails.var p = Promise.all([p1, p2, p3]);
- When the states of P1, P2 and P3 are all negative
resolved
The state of P isresolved
。 - When any one of P1, P2 or P3 is
rejected
,p
The state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of beingrejected
And the first one isreject
Will be passed to thep
The callback function of.
- When the states of P1, P2 and P3 are all negative
Specific examples are as follows:
-
Case 1:All successful cases
Promise.all([Promise.resolve('foo'),Promise.resolve('bar'),Promise.resolve('test')]) .then(function(result){ console.log (result); // the result is: [foo, bar, test]. That is, an array of all return values. }) .catch(function(error) { console.log ('error '); // will not be executed });
-
Case 2:Total or partial failure
Promise.all([Promise.resolve('foo'),Promise.reject('barError'),Promise.reject('testError')]) .then(function(result){ console.log (result); // successful callbacks will not be executed }) .catch(function(error) { console.log (error); // the result is barerror or testerror. That is, the first value to be rejected. });
3、 Common mistakes in use
- Forget to add. Catch ()
Generally, promise has the following two processing methods:
//Bad writing-------------
promise.then(function(data) {
// success
}, function (ERR) {// only handle errors that occur when promise is running. Unable to handle error in callback
// error
});
//Good writing------------
promise.then(function(data) {
// success
}). Catch (function (ERR) {// handle the error of promise and previous callback function
// error
});
Because errors thrown by promise are not passed to the outer code. When using the first method without catch, the error of successful callback cannot be handled. So a better way is to use it all the timecatch
method.
- Return is not used in then or catch functions
Here is a common mistake when using promise:
//------------Bad writing------------------
promise.then(function () {
getUserInfo(userId);
}).then(function () {
//You may want to use user information in this callback, but you may find that it doesn't exist at all
});
The above error occurs because of insufficient understanding of promise return and chained call.
Every promise will give you a then () method (or catch, they are just then (null )The grammar of sugar. Here we look inside the then () method
promise.then(function () {
return getUserInfo(userId);
}).then(function (userInfo) {
HadleUser(userInfo);
}).catch(function(error) {
console.log(error);
});
There are three things you can do in callbacks:
- Return to another promise
IfgetUserInfo
Returns a promise, thenHadleUser
It will be executed after the promise becomes resolved, with the return of the promise as the input parameter.
- Returns a synchronized value (or undefined)
getUserInfo
If a synchronous value is returned, the modified value will be packaged as a resolved promise,HadleUser
Will be executed immediately with getUserInfo as the input parameter.
- A synchronization error was thrown。
getUserInfo
If a synchronization error is returned, the error will be packaged as a project in the rejected state and finally caught in catch. hereHadleUser
Will not be executed.
- Promises lost
What do you think the following code will print out?
Promise.resolve('foo').then(Promise.resolve('bar')).then(function (result) {
console.log(result);
});
If you think the bar is printed, you’re wrong. It actually prints foo.
as a result ofWhen you pass a non function (such as a promise) value to then (), it will actually be interpreted as then (null), which will cause the previous promise result to be lost.
4、 Best practice summary
-
then
Forever in the methodreturn
Orthrow
- If
promise
There may be errors in the chain, so be sure to add themcatch
- Always transfer function to
then
Methods - Don’t take it
promise
Write nested
Reference link:
Promises is cool, but many people use it without understanding it