Catalog:
1, Promise overview
In short, Promise is a solution for asynchronous programming. Syntactically, Promise is an object from which messages for asynchronous operations can be obtained.
2, Benefits of using Promise
- It can avoid the nesting problem of multiple asynchronous calls (callback hell) and improve the readability of the code.
- promise provides a concise API to make asynchronous operations easier.
3, Promise basic usage
- Instantiate the Promise object, pass parameters in the constructor, which is used to handle asynchronous tasks.
- Two parameters, resolve and reject, are used to handle success and failure, and obtain the processing results through p.then.
var p = new Promise(function(resolve,reject){ // Call resolve() on success // Call reject() on failure }); p.then(function(ret){ //Get normal results from resolve },function(ret){} //Get error message from reject ));
Small case of practical operation:
<script type="text/javascript"> /* 1. Promise Basic use We use new to build a constructor of promise promise to receive a parameter, which is a function, and pass in two parameters: resolve and reject, which respectively represent the callback function after the asynchronous operation succeeds and the callback function after the asynchronous operation fails */ var p = new Promise(function(resolve, reject){ //2. This is used to implement the asynchronous task setTimeout setTimeout(function(){ var flag = false; if(flag) { //3. Normal conditions resolve('hello'); }else{ //4. Abnormal conditions reject('Error'); } }, 100); }); // 5 after the project instance is generated, you can use the then method to specify the callback functions of the resolved state and the reject state // In the then method, you can also return the data directly instead of the Promise object, and then you can receive the data in the later then method p.then(function(data){ console.log(data) },function(info){ console.log(info) }); </script>
4, Send Ajax request based on Promise
<script type="text/javascript"> /* Send Ajax request based on Promise */ function queryData(url) { # 1.1 Create a Promise Example var p = new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState != 4) return; if(xhr.readyState == 4 && xhr.status == 200) { # 1.2 Deal with normal conditions resolve(xhr.responseText); }else{ # 1.3 Handling exceptions reject('Server error'); } }; xhr.open('get', url); xhr.send(null); }); return p; } # In the then method, you can also directlyreturnData, not Promise Object, after then Data can be received in queryData('http://localhost:3000/data') .then(function(data){ console.log(data) # 1.4 If you want to continue chain programming, you need to return return queryData('http://localhost:3000/data1'); }) .then(function(data){ //Returns the result of the previous instance object console.log(data); return queryData('http://localhost:3000/data2'); }) .then(function(data){ console.log(data) }); </script>
5, Promise basic API
Example method
These APIs are all located in the function prototype and are instance methods, so they should be called with instances.
.then()
- Used to get the correct result after asynchronous task execution
.catch()
- Get exception information
.finally()
- Success or failure will be implemented (not official standard, supported by the latest Chrome)
<script type="text/javascript"> /* Promise Common API instance method */ // console.dir(Promise); function foo() { return new Promise(function(resolve, reject){ setTimeout(function(){ // resolve(123); reject('error'); }, 100); }) } // foo() // .then(function(data){ // console.log(data) // }) // .catch(function(data){ // console.log(data) // }) // .finally(function(){ // console.log('finished') // }); // -------------------------- // The two writing methods are equivalent foo() .then(function(data){ # Get the right results for asynchronous tasks console.log(data) },function(data){ # Get exception information console.log(data) }) # Success or failure will be implemented (not a formal standard) .finally(function(){ console.log('finished') }); </script>
Static method
.all()
- Promise.all() processes multiple asynchronous tasks concurrently, and the results can only be obtained after all tasks are executed.
- The Promise.all method takes an array as a parameter, and the objects (p1, p2, p3) in the array are promise instances (if not a promise, the item will be converted to a promise with Promise.resolve). Its state is determined by these three promise instances
- The returned result is an array, and the order of the results corresponds to the order of the Promise instance object of the array.
.race()
-
Promise.all() processes multiple asynchronous tasks concurrently, and results can be obtained as long as one task is completed.
-
The Promise.race method also takes an array as an argument. When the state of an instance in p1, p2 and p3 changes (to fully or rejected), the state of p changes accordingly. And pass the return value of the first promise that changes state to the callback function of p
-
The returned result is an array, and the order of the results corresponds to the order of the Promise instance object of the array.
<script type="text/javascript"> /* Promise Common API object methods */ // console.dir(Promise) function queryData(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState != 4) return; if(xhr.readyState == 4 && xhr.status == 200) { // Deal with normal conditions resolve(xhr.responseText); }else{ // Handling exceptions reject('Server error'); } }; xhr.open('get', url); xhr.send(null); }); } var p1 = queryData('http://localhost:3000/a1'); var p2 = queryData('http://localhost:3000/a2'); var p3 = queryData('http://localhost:3000/a3'); Promise.all([p1,p2,p3]).then(function(result){ // The parameters [p1,p2,p3] in all correspond to the returned result one by one ["Hello Tom", "Hello Jerry", "Hello spice"] console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"] }) Promise.race([p1,p2,p3]).then(function(result){ // Because P1 executes faster, Promise's then() gets the result 'P1'. p2,p3 are still executing, but the result will be discarded. console.log(result) // "HELLO TOM" }) </script>
If you are also learning about the front end, please pay attention to the blogger and learn more about the front end~