ES6 - Promise Detailed Explanation and Usage

1. What is Promise

Promise is a solution for ES6 asynchronous programming (currently the most advanced solution is the combination of async and await (ES8), but they are based on promise). Syntactically, Promise is an object or a constructor. Used to encapsulate asynchronous operations and get their success or failure results.

2. Why use promise

The most important and main scenario is ajax and axios requests. Generally speaking, due to the difference in network speed, the time you get the return value may be different, but the code we will execute next depends on the return value of the previous request. At this time, we need to wait until the result comes out. How to continue. 

Three, the benefits of promise

Prevent callback hell;

Improve code readability;

Perform asynchronous operations like synchronous operations

 Fourth, the three states of promise

1.pending: Waiting, or in progress, indicating that the result has not been obtained
2.resolved(Fulfilled): It has been completed, indicating that we have obtained the result we want, and can continue to execute
3.rejected: It also indicates that the result has been obtained, but Declined because the result was not what we wanted 

    <script>
        function fn(flag) {
            //构造函数
               return new Promise(function(resolve, reject) {
                if (flag === true) {
                    resolve('promise状态为成功!')
                };
                if (flag === false) {
                    reject('promise状态失败!')
                };
            })
        }
 
        console.log(fn(true));
    </script>

 

5. The usage of promise 

1. Instance method of promise

①then() gets the correct result of the asynchronous task

②catch() to obtain exception information
③finally() will be executed whether it is successful or not (it is not yet a formal standard)
 Note: the then method can accept two functions, the first function is a callback function with a promise status as success, and the second function is a promise status Callback function for failure (you can not write it, generally use the catch method to capture the exception information that the promise status is failed)

<script>
    let pro = new Promise((resolve, reject) => {
        if (Math.random() > 0.5) {
            resolve("i'm resolve");
        } else {
            reject("i'm reject");
        }
    })

    pro.then((res) => {
        console.log(res);
    }).catch((err) => {
        console.log(err);
    })
</script>

the case

    Goal: get a description of the sniper movie

    process:

    1. Login first

    2. Request director information to find director Zhang's id

    3. Request movie info to find description 

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    // 1.登录
    // let myLogin = () => new Promise()
    function myLogin() {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'get',
                url: '../json/login.json',
                success(res) {
                    resolve(res);
                },
                error(err) {
                    reject(err);
                }
            })
        })
    }

    // 2.导演列表
    function myDirector() {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'get',
                url: '../json/director.json',
                success(res) {
                    resolve(res);
                },
                error(err) {
                    reject(err);
                }
            })
        })
    }

    // 3.电影信息
    function myFilm(id) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'get',
                url: '../json/' + id + '.json',
                success(res) {
                    resolve(res);
                },
                error(err) {
                    reject(err);
                }
            })
        })
    }

    myLogin().then(res => {
        return myDirector();
    }).then(res => {
        return myFilm(3);
    }).then(res => {
        console.log(res);
    }).catch(err => {
        console.log(err);
    })
</script>

 2. The object method of promise (p1, p2, p3 are instance objects of promise)

①Promise.all() processes multiple asynchronous tasks concurrently, and the results can only be obtained after all tasks are executed

Promise.all( [p1,p2,p3] ) .then ( (result) => {
    consoleog (result)
})

②Promise.race() processes multiple asynchronous tasks concurrently, as long as one task is completed, the result can be obtained

Promise.race ( [p1,p2,p3] ).then ( (result)=>{
     console. log (result)
})

6. Summary

1. Promise is actually an object or a constructor.
2. The appearance of promise (es6) is to solve problems such as asynchronous programming and callback hell. The appearance of async and await (ES8) is an ultimate solution to asynchronous programming based on promise. Solution (simplified code, etc.)
3. In the front end, both ajax and axios use asynchronous programming, and axios is based on promises, so you must master promises and use async and await with promises

おすすめ

転載: blog.csdn.net/Cc200171/article/details/125295823