What is promise, use and implementation of promise

Posted by willdk on Thu, 17 Feb 2022 17:15:06 +0100

What is promise, use and implementation of promise

What is promise
It is a new constructor in es6, which contains an asynchronous operation
promise is a solution of asynchronous programming, which solves the problem of hell callback. It is a way of chain transfer

Promise is simply a container that holds the results of an event (usually an asynchronous operation) that will not end in the future.

promise is an object from which the final state (success or failure) of an asynchronous operation can be obtained.

Promise is a constructor that provides a unified API. It has all, reject, resolve and other methods on its own, and then, catch and other methods on its prototype.

promise has three states

pending initial state

Fully successful status

rejected failed status
For the above three states, only the result of asynchronous operation can determine which state it is currently, and no other operation can change this state

Once the Promise state changes, it will not change again. This result can be obtained at any time. The state cannot be reversed. It can only be changed from pending to fully or from pending to rejected

promise creation
Use new to create a promise object.
Promise accepts a "function" as a parameter. The two parameters of the function are resolve and reject. These two functions are called callback functions

The resolve function is used to call when the asynchronous operation is successful and pass the result of the asynchronous operation as a parameter;

The reject function is used to call when the asynchronous operation fails and pass the error reported by the asynchronous operation as a parameter

then() method: the then method is to separate the original callback writing method and execute the callback function by chain call after the asynchronous operation is executed.

catch() method: when executing the callback of resolve (that is, the first parameter in then above), if an exception is thrown (the code is wrong), it will not report an error and get stuck js, but will enter this catch method.

all() method: Promise's all method provides the ability to execute asynchronous operations in parallel, and the callback is executed only after all asynchronous operations are executed.

race() method: Race literally means race. The usage of race is the same as that of all, except that all does not execute the then callback until all asynchronous operations are completed. In race, as long as an asynchronous operation is completed, the then callback will be executed immediately.

promise simple example

//Promise asynchronously encapsulates ajax
<script>
    function Feach(method,  ) {
        let p = new Promise((resolve, reject) => {
            // Handwritten native ajax
            let xhr = new XMLHttpRequest(); //Create ajax request
            xhr.open(method, url, true);  //Initiate request
            xhr.send(null); //Send the request. The sent parameter is empty
            //Asynchronous callback function
            xhr.onreadystatechange = function () {

                //readystate: the request returns five statuses
                // send() method not initialized: 0
                // 1 (load): the send() method has been called and the request is being sent
                // 2 (loading completed): the execution of the send() method is completed and all response contents have been received
                // 3 (interaction): parsing response content
                // 4 (completion): the response content is parsed and can be called on the client
                if (xhr.readyState == 4 && xhr.status == 200) {  
                    resolve(xhr.responseTex t);  //responseText: get response data in character form responseXML: get response data in XML form
                } else if (xhr.status == 400) {
                    reject('fail')
                }
            }
        })
        return p;
    }

    let url = "http://wthrcdn.etouch.cn/weather_mini?city=%E5%8C%97%E4%BA%AC";

    Feach('get',url).then(res => {
        console.log(res)
    }, err => {
        console.log(err)
    })

</script>

<script>
	//promise asynchronously loading pictures
	
    // Create a function
    function requestImg(){
        // Create a promise object
        var p= new Promise(function(resolve,reject){
            // Create an image object
            var img=new Image();
            // The image performs a successful callback after the page is loaded
            img.onload=function(){
                resolve(img);
            }
            img.src="./qzone.png"
        });
        return p;
    }

    //Delay function, which is used to time the request
    function timeout(){
        // Create a promise object and execute the wrong callback if the request times out
        var p=new Promise(function(resolve,reject){
            setTimeout(()=>{
                let span=documnet.createElement('span')
                span.innerText='Loading failed'
                resolve(span);
            },5000);
        });
        return p;
    }
    // After promise is executed once, if the execution is successful, execute the then method; otherwise, execute the catch method
    Promise.race([requestImg(),timeout()]).then(function(results){
        console.log(results);
    }).catch(function(reason){
        console.log(reason)
    });
    //The requestImg function of the above code asynchronously requests a picture. The timeout function is an asynchronous operation with a delay of 5 seconds. We put them together in race
    //If the picture request is successful within 5 seconds, enter the then method and execute the normal process.
    // If the picture is not returned successfully within 5 seconds, enter catch and report the message of "picture request timeout"

</script>

Topics: Javascript