JavaScript function promise ES6
I don't say what Promise is. There are various versions on the Internet, so here I just want to record the execution process of Promise and the precautions for use, and add some personal understanding
By the way, I also wrote an article《 Understand the Generator in ES6 》
Workflow
Preceding code
function asyncFunction(){ return new Promise(function(resolve,reject){ setTimeout(function(){ resolve('Async Hello World'); },16); }); } asyncFunction().then(function(value){ console.log(value); }).catch(function(error){ console.log(error); });
In the code, we use the constructor Promise
To create a new promise object; Then, when the promise object is executed, the .then
Callback function when calling return value
asyncFunction
This function will return the promise object. For this promise object, we call its then
Method to set the callback function after resolving, catch
Method to set the callback function when an error occurs
The promise object will be displayed in the setTimeout
The next 16ms is resolve
, then the callback function of then will be called and output Async Hello world
state
use new Promise
The instantiated promise object has the following three states. The left side is the term defined in the ES6 Promises specification, and the right side is the term describing the status in Promises/A+
1、 "has-resolution" - Fulfilled
Resolve (successful). OnFulfilled is called
2、 "has-rejection" - Rejected
Reject (failure). OnRejected is called
3.、"unresolved" - Pending
It is neither resolved nor rejected. That is, the initialization status of the promise object after it has just been created
In addition, either of the two statuses, Fulfilled and Rejected, can be expressed as Settled (unchanged)
4、Settled
Resolve or reject.
actual combat
Grammatical sugar
Promise.resolve
Promise.resolve(42);
It can be considered as the syntax sugar of the following code
new Promise(function(resolve){ resolve(42); });
In this code resolve(42);
The promise object will immediately enter the confirmed (resolved) state, and the forty-two
Pass to the specified in then onFulfilled
function
method Promise.resolve(value);
The return value of is also a promise object
Promise.reject
Promise. reject (new Error)
It is the syntax sugar of the following code
new Promise(function(resolve,reject){ Reject (new Error); });
Thenable
The concept of Theable is mentioned in ES6 Promises, which is very similar to promise
As we sometimes call it .length
The non array object of the method is Array like, and the enable refers to a .then
Object of method
This mechanism to convert the tenable object into a promise object requires that the then
The method should be the same as the then
The method has the same function and processing process. When the tenable object is converted to the promise object, the original then
method
Then is asynchronous
The method call specified in. then is asynchronous, as follows
var promise = new Promise(function (resolve){ console.log("inner promise"); resolve(42); }); promise.then(function(value){ console.log(value); }); console.log("outer promise");
After execution
inner promise outer promise forty-two
In order to avoid possible confusion caused by simultaneous use of synchronous and asynchronous calls, Promise stipulates in the specification Promise can only use asynchronous call mode , so Promise ensures that every call is made asynchronously
Chain writing
Promise can be written in the form of method chain, as follows
aPromise.then(function taskA(value){ // task A }).then(function taskB(vaue){ // task B }).catch(function onRejected(error){ console.log(error); });
At first glance from the code, aPromise.then(...).catch(...)
It seems to be aimed at the original aPromise
Object makes a series of method chain calls
But in fact, no matter then
still catch
Method call, a new promise object is returned
Let's determine whether the two methods return a new promise object, as shown below
var aPromise = new Promise(function (resolve) { resolve(100); }); var thenPromise = aPromise.then(function (value) { console.log(value); }); var catchPromise = thenPromise.catch(function (error) { console.error(error); }); console.log(aPromise === thenPromise); console.log(thenPromise === catchPromise);
Execute Return
false false one hundred
===
It is a strict equality comparison operator. We can see that these three objects are different from each other, which proves that then
and catch
Both returned promise objects different from the caller
Promise.all
Promise.all
Receives an array of promise objects as a parameter. When all promise objects in this array change to the resolve or reject state, it will call .then
method
function timerPromisefy(delay) { return new Promise(function(resolve) { setTimeout(function() { resolve(delay); }, delay); }); } var startDate = Date.now(); Promise.all([ timerPromisefy(1), timerPromisefy(32), timerPromisefy(64), timerPromisefy(128) ]).then(function(values) { console.log(Date.now() - startDate + 'ms'); console.log(values); });
Execute Return
129ms [ 1, 32, 64, 128 ]
If all promises in the promise object array change to the resolved state, it takes at least 128ms
From the above results, we can see that the promises passed to Promise.all are not executed one by one in sequence, but simultaneously and in parallel
Promise.race
Promise.race
How to use and Promise.all
Similarly, receive a promise object array as a parameter. When one of the promise objects enters the FullFilled or Rejected state, it will call .then
method
function timerPromisefy(delay) { return new Promise(function(resolve) { setTimeout(function() { resolve(delay); }, delay); }); } Promise.race([ timerPromisefy(1), timerPromisefy(32), timerPromisefy(64), timerPromisefy(128) ]).then(function(value) { console.log(value); });
Execute Return
one
The above code creates four promise objects. These promise objects will change to the confirmed state after 1ms, 32ms, 64ms and 128ms respectively, that is, FullFilled. After the first one changes to the confirmed state 1ms, .then
The registered callback function will be called, and the promise object that determines the status will call resolve(1)
Therefore, the value passed to value is also 1, which will be printed on the console one
come
It should be noted that
Promise.race
The execution of other promise objects will not be canceled after the first promise object becomes Fulfilled
supplement
- If promise. then (onFulfilled, onRejected) is used
If an exception occurs in onFulfilled, it cannot be caught in onRejected
- In the case of promise. then (onFulfilled). catch (onRejected)
The exception generated in then can be captured in. catch
- There is no difference between. then and. catch in essence
It needs to be used separately and together
summary
When I read JavaScript You Don't Know (Medium Volume), I had already mentioned it, but I didn't understand it very much. So I read the mini book again, and then turned over the medium volume. I understood it all. I think there is nothing to summarize. Maybe it would be better to write a demo
More content, so far~
reference resources
- liubin.org/promises-book/
Basically, the whole book has been read, and some references in the book have also been read
This article is written by Chakhsu Lau Creation, adoption Knowledge Sharing Attribution 4.0 International License Agreement.
All articles on this website are original or translated by this website, except for the reprint/source. Please sign your name before reprinting.