promise meanings:
The so-called Promise
, it simply is a container, which holds the event will end sometime in the future (usually an asynchronous operation) results.
Syntactically, Promise is an object, you can get messages from the asynchronous operation of it. Promise to provide a unified API, a variety of asynchronous operations can be handled the same way.
promise basic usage:
Promise
Constructor takes a function as a parameter, two parameters of the function are respectively resolve
and reject
. They are two functions provided by the JavaScript engine, you do not have to deploy.
Function is to resolve the role of the state of the object from Promise "unfinished" to "success" (i.e., changed from pending resolved), upon successful call asynchronous operation, and the result of the asynchronous operation, to pass out as a parameter;
Function is to reject the role of the state of the object from Promise "unfinished" to "failed" (i.e., changed from pending Rejected), invoked when an asynchronous operation fails, and the asynchronous operation errors may be, as a parameter to pass out .
Promise
After the instance generation, you can then
specify methods resolved
state and a rejected
callback status.
const promise = new Promise(function(resolve, reject) { // ... some code if (/* 异步操作成功 */){ resolve(value); } else { reject(error); } }); promise.then(function(value) { // success }, function(error) { // failure });
After the new promise will be executed immediately
var promise = new Promise(function(resolve, reject) { console.log('Promise instance'); resolve(); }); promise.then(function() { console.log('resolved result'); }); for(var i=0;i<100;i++) { console.log(i);
} /* Promise instance 1 2 3 ... 99 100 resolved result */
resolve
Addition to the normal function of the parameters values, but also may be another example of Promise, such like this.
const p1 = new Promise(function (resolve, reject) { // ... }); const p2 = new Promise(function (resolve, reject) { // ... resolve(p1); })
The above code, p1
and p2
are examples of Promise, but p2
the resolve
method p1
as a parameter, i.e. a result of the asynchronous operation is another return asynchronous operation.
Note that at this time p1
the state will transfer to p2
, say, p1
the state determines the p2
state. If the p1
state is pending
, then the p2
callback function will wait for p1
a change of state; if p1
the state is already resolved
or rejected
, the p2
callback function will be executed immediately.
promise.prototype,then()
Promise instance has then
methods, i.e., then
methods in the prototype object is defined Promise.prototype
on. Its role is to add callback function for the state change Promise instance.
As mentioned above, then
the first argument of the method is resolved
a callback function of the state, and the second parameter (optional) is the rejected
callback status.
then
Method returns a new Promise
instance (note, not the original Promise
instance). It can be written using the chain, i.e. then
after the method then calls another then
method.
getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... });
The above code uses the then
method, the two callback functions specified sequence. After the first callback is completed, the result will be returned as a parameter passed in the second callback.
The use of the chain then
, you can specify a set of callback functions in the order called. At this time, before a callback function, there is still a possible return of Promise
the object (that is asynchronous operation), then after a callback function, it will wait for the Promise
object's status changes, will be called.
getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function (comments) { console.log("resolved: ", comments); }, function (err){ console.log("rejected: ", err); });
In the above code, the first then
method specified callback function returns another Promise
object. At this time, the second then
method specified callback function will wait for the new Promise
object state changes. If changed resolved
, it calls the first callback, if the status changes rejected
, call the second callback function.
If the function of the arrow, the above code can be written more succinctly.
the getJSON ( "/post/1.json" ) .then (
POST => the getJSON (post.commentURL) ) .then (
Comments => the console.log ( "resolved:" , Comments), ERR => the console.log ( " Rejected: " , ERR) );
promise.prototype.catch()
getJSON ( '/ posts.json'). the then ( function (Posts) { // ... }). the catch ( function (error) {
// an error occurred while processing a previous callback getJSON and run console.log ( 'error occurs!' , error); });
In the above code, the getJSON method returns a Promise object, if the object status becomes resolved, then the method specified callback function will be called;
If the asynchronous operation throws an error, status changes rejected, will call the catch method specified callback function, to deal with this error. In addition, then the method specified callback function, if the operation throws an error, it will be caught catch method.
p.then((val) => console.log('fulfilled:', val)) .catch((err) => console.log('rejected', err)); // 等同于 p.then((val) => console.log('fulfilled:', val)) .then(null, (err) => console.log("rejected:", err));
In general, do not then
defined inside a method callback Reject state (i.e., then
the second argument) is always used catch
method.
// bad promise .then(function(data) { // success }, function(err) { // error }); // good promise .then(function(data) { //cb // success }) .catch(function(err) { // error });
In the above code, the second writing is better than the first writing, writing is the second reason can capture the foregoing then
method performed errors, are closer to synchronous writing ( try/catch
). It is therefore recommended to always use catch
the method, instead of using the then
method of the second parameter.
promise.protype.finally
finally
Regardless of the method used to target Promise final state, the operation will be performed specified. The standard method is introduced ES2018.
promise .then(result => {···}) .catch(error => {···}) .finally(() => {···});
promise.all
Promise.all
A method for multiple instances Promise, Promise packaged into a new instance.
const p = Promise.all([p1, p2, p3]);
The above code, the Promise.all
method takes an array as a parameter, p1
, p2
, p3
are examples Promise, if not, the following will be called first mentioned Promise.resolve
method, the parameter into Promise instance, further processing. ( Promise.all
Method parameters may not be an array, but must have the Iterator interface, and each member is returned Promise instance.)
p
State by the p1
, p2
, p3
determined, is divided into two cases.
(1) Only p1
, p2
, p3
is turned into a state fulfilled
, p
the state will become a fulfilled
this case p1
, p2
, p3
the return value consisting of an array, is passed to the p
callback function.
(2) long p1
, p2
, p3
being there is to be a rejected
, p
a state becomes rejected
, the first case is reject
the return value of the instance, is passed to the p
callback function.
promise.race()
Promise.race
The method also multiple instances Promise, Promise packaged into a new instance.
const p = Promise.race([p1, p2, p3]);
In the above code, as long as p1
, p2
, p3
in one instance first to change state, p
the state will change accordingly. Promise to return the value of that instance of the first to change, it is passed to the p
callback function.
Promise.race
Parameters and methods Promise.all
the same way, if not Promise instance, it will first call the below mentioned Promise.resolve
method, the parameters into Promise instance, further processing.
Here is an example, if the result is not obtained within the specified time, the state will be changed Promise reject
otherwise becomes resolve
.
const p = Promise.race([ fetch('/resource-that-may-take-a-while'), new Promise(function (resolve, reject) { setTimeout(() => reject(new Error('request timeout')), 5000) }) ]); p .then(console.log) .catch(console.error);