Reference for instance object, function object, callback and other related knowledge: this
Promise introduction
- Promise is a new technology (ES6 specification) and a new solution for asynchronous programming in JS (the old solution was to simply use callback functions).
- Grammatically, Promise is a constructor (I have all, reject and resolve methods, and then, catch and other methods on the prototype).
- Functionally, Promise object is used to encapsulate an asynchronous operation and obtain its success / failure result value.
- Asynchronous programming: ① fs file operation ② database operation ③ Ajax ④ setInterval
- Promise is more flexible in specifying callback functions:
Old: must be specified before starting an asynchronous task
Promise: start asynchronous task = > return promise object = > bind callback function to promise object (you can even specify / multiple after the end of asynchronous task) - Promise supports chain calls, which can solve the problem of callback hell (callback functions are nested calls, and the result of asynchronous execution of external callback functions is the condition of nested callback execution)
<script> //Callback hell doSomething(function(result){ doSomethingElse(result,function(newResult){ doThirdThing(newResult,function(finalResult){ console.log('Gotthefinalresult:'+finalResult) },failureCallback) },failureCallback) },failureCallback) //Use promise's chained call to solve the callback problem doSomething().then(function(result){ return doSomethingElse(result) }) .then(function(newResult){ return doThirdThing(newResult) }) .then(function(finalResult){ console.log('Gotthefinalresult:'+finalResult) }) .catch(failureCallback) // async/await: the ultimate solution to callback hell asyncfunctionrequest(){ try{const result=awaitdoSomething() const newResult=awaitdoSomethingElse(result) constfinalResult=awaitdoThirdThing(newResult) console.log('Gotthefinalresult:'+finalResult) }catch(error){ failureCallback(error) } } </script>
Promise basic process
- Promise encapsulates an asynchronous operation. When it succeeds, it calls resolve and passes the result to the resolve function. When it fails, it calls reject and passes the failure reason or error to the reject function.
- Then process the success or failure results in the then function. Success (the result data is generally called value) calls the code in the first callback function, and failure (the result data is generally called reason) calls the code in the second callback function.
Basic use of Promise
Encapsulating AJAX operations
//Create Promise const p = new Promise((resolve, reject) => { //1. Create object const xhr = new XMLHttpRequest(); //2. Initialization xhr.open('GET', 'https://api.apiopen.top/getJoke'); //3. Send xhr.send(); //4. Process response results xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ //Judgment response status code 2xx if(xhr.status >= 200 && xhr.status < 300){ //Console output response body resolve(xhr.response); }else{ //Console output response status code reject(xhr.status); } } } }); //Call the then method p.then(value=>{ console.log(value); }, reason=>{ console.warn(reason); });
Encapsulate setInterval operation
<body> <div class="container"> <h2 class="page-header">Promise First experience</h2> <button class="btn btn-primary" id="btn">Click lucky draw</button> </div> <script> //Generate random number function rand(m,n){ return Math.ceil(Math.random() * (n-m+1)) + m-1; } //Click the button, and it will display whether to win the prize after 1s (30% probability) const btn = document.querySelector('#btn'); btn.addEventListener('click', function(){ //timer // setTimeout(() => { // //Gets a random number from 1 - 100 // let n = rand(1, 100); // if(n <= 30){ // alert('congratulations, the prize is 100000 RMB Rolls Royce coupon '); // }else{ // alert('Keep going '); // } // }, 1000); //Promise formal implementation //1) Create promise object (pending state) and specify the executor function const p = new Promise((resolve, reject) => { //2) Start an asynchronous task in an actuator function setTimeout(() => { //Gets a random number from 1 - 100 let n = rand(1, 100); if(n <= 30){//3.1) if it is successful, call resolve(), specify the successful value, change to the resolved state, and set the state of promise object to "successful" resolve(n); }else{//3.2) if it fails, call reject(), specify the reason for the failure, change to the rejected state, and set the state of the promise object to "failed" reject(n); } }, 1000); }); console.log(p); //Call the then method p.then((value) => {//The successful callback function onResolved gets the successful vlaue alert('congratulations, The prize is 100000 RMB Rolls Royce coupons, Your winning number is ' + value); }, (reason) => {//The failed callback function onRejected gets the failed reason alert('make persistent efforts, Your number is ' + reason); }); }); </script> </body> </html>
Promise API
1.Promise constructor: Promise(executor) {}
- executor function: resolve, reject = > {}
- resolve function: the function reset (value) called when the internal definition succeeds
- reject function: the function called when the internal definition fails (reason)
- Note: the executor is the executor. It will immediately synchronize the callback within Promise. The asynchronous operation resolve/reject is in the executor
2. Promise.prototype.then method: p.then(onResolved, onRejected)
- onResolved function: successful callback function (value) = > {}
- onRejected function: failed callback function (reason) = > {}
- Note: specify two callbacks (success + failure): the success callback used to get the success value and the failure callback used to get the failure reason, and return a new promise object
3. Promise.prototype.catch method: (onrejected) = > {}
- onRejected function: failed callback function (reason) = > {}
- Note: the syntax of then() is equivalent to then(undefined, onRejected)
new Promise((resolve, reject) => { // excutor executor function setTimeout(() => { if(...) { resolve('Successful data') // resolve() function } else { reject('Failed data') //reject() function } }, 1000) }).then( value => { // onResolved() function console.log(value) // Successful data }).catch( reason => { // onRejected() function console.log(reason) // Failed data } )
4. Promise.resolve method: (value) = > {}
value: successful data or promise Object Description: returns a successful / failed promise object
<script> //If the passed in parameter is an object of non promise type, the result returned is a successful promise object let p1 = Promise.resolve(521); console.log(p1); //If the passed in parameter is Promise object, the result of the parameter determines the result of resolve let p2 = Promise.resolve(new Promise((resolve, reject) => { // resolve('OK');// success reject('Error');//fail })); console.log(p2); p2.catch(reason => {//Handling in case of failure console.log(reason); }) </script>
5.Promise.reject method: (reason) = > {}
Reason: reason for failure Description: a failed promise object is returned
<script> // let p = Promise.reject(521); // let p2 = Promise.reject('iloveyou'); let p3 = Promise.reject(new Promise((resolve, reject) => { resolve('OK'); })); console.log(p3); </script>
Promise.resolve()/Promise.reject() method is a syntax sugar used to get promise objects quickly.
//Generate a promise object with a success value of 1 new Promise((resolve, reject) => { resolve(1) }) //amount to const p1 = Promise.resolve(1) const p2 = Promise.resolve(2) const p3 = Promise.reject(3) p1.then(value => {console.log(value)}) // 1 p2.then(value => {console.log(value)}) // 2 p3.catch(reason => {console.log(reason)}) // 3
6.Promise.all method: (promises) = > {}
Promises: an array containing n promises. Note: a new promise is returned. It will succeed only if all promises are successful. The result is an array of successful results; As long as one fails, it will fail directly, and the result is the result of the failed object.
let p1 = new Promise((resolve, reject) => { resolve('OK'); }) let p2 = Promise.resolve('Success'); let p3 = Promise.resolve('Ohhhhh'); const result = Promise.all([p1, p2, p3]); console.log(result);
7.Promise.race method: (promises) = > {}
Promises: an array containing n promises. Description: returns a new promise. The result state of the first completed promise is the final result state.
<script> let p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('OK'); }, 1000); }) let p2 = Promise.resolve('Success'); let p3 = Promise.resolve('Oh Yeah'); //call const result = Promise.race([p1, p2, p3]); console.log(result); </script>