Promise is a must for beginners from entry to mastery

Posted by dardsemail on Thu, 23 Sep 2021 10:22:13 +0200

Reference for instance object, function object, callback and other related knowledge: this

Promise introduction

  1. 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).
  2. Grammatically, Promise is a constructor (I have all, reject and resolve methods, and then, catch and other methods on the prototype).
  3. Functionally, Promise object is used to encapsulate an asynchronous operation and obtain its success / failure result value.
  4. Asynchronous programming: ① fs file operation ② database operation ③ Ajax ④ setInterval
  5. 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)
  6. 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)
	//Callback hell
	//Use promise's chained call to solve the callback problem
		return doSomethingElse(result)
		return doThirdThing(newResult)
	// async/await: the ultimate solution to callback hell
		try{const result=awaitdoSomething()
			const newResult=awaitdoSomethingElse(result)

Promise basic process

  1. 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.
  2. 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'GET', '');
    //3. 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
                //Console output response status code
//Call the then method
}, reason=>{

Encapsulate setInterval operation

    <div class="container">
        <h2 class="page-header">Promise First experience</h2>
        <button class="btn btn-primary" id="btn">Click lucky draw</button>
        //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(){
            // 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"
                    }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"
                }, 1000);

            //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);

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)
	 value => { // onResolved() function
	  console.log(value) // Successful data
	 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

    //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);
    //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
    p2.catch(reason => {//Handling in case of failure

5.Promise.reject method: (reason) = > {}

Reason: reason for failure Description: a failed promise object is returned

    // let p = Promise.reject(521);
    // let p2 = Promise.reject('iloveyou');
    let p3 = Promise.reject(new Promise((resolve, reject) => {

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) => {
//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) => {
let p2 = Promise.resolve('Success');
let p3 = Promise.resolve('Ohhhhh');

const result = Promise.all([p1, p2, p3]);

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.

    let p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
        }, 1000);
    let p2 = Promise.resolve('Success');
    let p3 = Promise.resolve('Oh Yeah');

    const result = Promise.race([p1, p2, p3]);


Topics: Front-end Promise