JavaScript Chapter 20 Promise

Promise

  • Promise is a class provided by ES6. It is a solution for asynchronous programming. It does not refer to a method of converting asynchronous to synchronous . The purpose is to write complex asynchronous tasks more elegantly.

advantage

1. The state of the subject is not affected by the outside world

  • Three states
    pending: in progress
    fulfilled: successfully rejected:
    failed
    Promise means promise, what does promise? That is, only the result of asynchronous operation can determine the current state, and no other operation can change this state

2. Once the state is changed, it will not change again, and the result can be obtained at any time

  • There are only two cases for the change of Promise status: pending to fulfilled and pending to reject
  • As long as these two situations occur, the state will not change, and the result will always be maintained. At this time, it is called resolved (finalized), and this result can be obtained by adding a callback function to the Promise object (unlike events, events If you miss it and listen again, you won’t get any results)

Disadvantage

1. Promise cannot be cancelled

  • Once it is created, it must be executed immediately and cannot be canceled midway.

2. Wrong judgment

  • If the callback function is not set, the error thrown inside the Promise will not be reflected to the outside

3. Unpredictable state

  • When in the pending state, it is impossible to know which state it is currently progressing to, whether it has just started or is about to be completed

One, construct Promise

  • grammar
new Promise(function (resolve, reject) {
    
    
    // to do...
});
  • The Promise constructor has only one parameter, which is a function . This function will be run asynchronously directly after construction, so we call it the start function. The start function contains two parameters resolve and reject. When the Promise is constructed, the start Function will be executed asynchronously
  • Both resolve and reject are functions (provided by the JavaScript engine, don’t need to be deployed by yourself), in which resolve means everything is normal, that is, it is called when the asynchronous function is successfully operated, and the result of the asynchronous operation is passed as a parameter, and reject is when an exception occurs The called is called when the asynchronous operation fails, and the error reported by the asynchronous operation is passed as a parameter
  • You can place a parameter in resolve() to pass a value to the next then, and the function in then can also return a value to pass to then, but if what is returned in then is a Promise object, then the next then will be equivalent Operate on the returned Promise
  • The reject() parameter usually passes an exception to the subsequent catch function to handle the exception
  • The scope of resolve and reject is only the initial function, excluding then and other sequences
  • resolve and reject cannot stop the start function, you should use return

Two, Promise method

1. then()

  • then() can add the function in the parameter to the normal execution sequence of the current Promise
  • The function passed in then() will be executed in sequence, and any exception will jump directly to the catch sequence
  • How to interrupt the then block: The then block will be executed in the downward order by default, return cannot be interrupted, and can be interrupted by jumping to catch by throwing
  • The then block can be used multiple times, but the catch block will only execute the first one unless there is an exception in the catch block, so it is best to arrange only one catch and finally block
  • When we need to call an asynchronous task, we need to write another then instead of programming in the current then

2. catch()

  • catch() is to set the exception handling sequence of Promise

3. finally()

  • finally() is a sequence that must be executed at the end of the Promise execution
  • The sequence of then, catch, and finally can be reversed, but this is not recommended. It is best to write the program in the order of then-catch-finally

Three, function waterfall

  • The program implemented with "function waterfall" is a particularly cumbersome matter for maintenance or exception handling, and it will make the indentation format very redundant
  • For example
setTimeout(function () {
    
    
    console.log("l");
    setTimeout(function () {
    
    
        console.log("z");
        setTimeout(function () {
    
    
            console.log("j");
        }, 3000);
    }, 2000);
}, 1000);

Fourth, use Promise to improve

  • With the Promise object, we can express asynchronous operations in a synchronous operation process, thereby avoiding nested callback functions. In addition, the Promise object provides a unified interface, making it easier to control asynchronous operations
  • Initial improvement
new Promise(function (resolve, reject) {
    
    
    setTimeout(function () {
    
    
        console.log("l");
        resolve();
    }, 1000);
}).then(function () {
    
    
    return new Promise(function (resolve, reject) {
    
    
        setTimeout(function () {
    
    
            console.log("z");
            resolve();
        }, 2000);
    });
}).then(function () {
    
    
    setTimeout(function () {
    
    
        console.log("j");
    }, 3000);
});
  • Final improvement
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promiseTest</title>
    <script>
        /*冗余*/
        // setTimeout(function () {
    
    
        //     console.log("m");
        //     setTimeout(function () {
    
    
        //         console.log("a");
        //         setTimeout(function () {
    
    
        //             console.log("y");
        //         },3000)
        //     },2000)
        // },1000)

        /*初步改进*/
        // resolve 代表一切正常,reject 是出现异常时所调用的
        // new Promise(function (resolve, reject) {
    
    
        //     setTimeout(function () {
    
    
        //         console.log("m");
        //         resolve();
        //     }, 1000);
        // }).then(function () {
    
    
        //     return new Promise(function (resolve, reject) {
    
    
        //         setTimeout(function () {
    
    
        //             console.log("a");
        //             resolve();
        //         }, 2000);
        //     });
        // }).then(function () {
    
    
        //     setTimeout(function () {
    
    
        //         console.log("y");
        //     }, 3000);
        // });

        /*最终优化*/
        // 使用 Promise 函数
        function print(delay, message) {
    
    
            // must write return(to return Promise object)
          return new Promise(function (resolve, reject) {
    
    
                setTimeout(function () {
    
    
                    console.log(message);
                    resolve();
                }, delay);
            });
        }
		
		// 实例
        print(1000,"m").then(function (){
    
    
            return print(2000,"a");
        }).then(function () {
    
    
            print(3000,"y"); // 对上面返回的Promise对象进行操作
        })

    </script>
</head>
<body>
    
</body>
</html>

Five, asynchronous function (async function)

  • An asynchronous function is a function that is executed asynchronously through an event loop and returns an implicit Promise as its result
  • grammar
async function name([param[, param[, ... param]]]) {
    
     statements }

1. Use asynchronous functions to optimize examples

async function asyncFunc() {
    
    
    await print(1000, "m");
    await print(4000, "a");
    await print(3000, "y");
}
asyncFunc();
  • The await instruction can be used in the asynchronous function async function. The await instruction must be followed by a Promise . The asynchronous function will pause during the Promise operation and continue to run until the end of its operation. That is, the await instruction suspends the execution of the asynchronous function and waits for the execution of the Promise. The result is returned, the execution of the asynchronous function is resumed after the result is returned , and the await instruction is only valid in async functions. If it is used outside the asynchronous function, a syntax error will be thrown

2. The try-catch block handles exceptions

  • Return a promise object, and return the value of the asynchronous function (if the asynchronous function is resolve, return the value of the resolve; if an exception is thrown, throw the reject exception declared in the asynchronous function)
async function testA(){
    
    
    try {
    
    
        await new Promise(function (resolve, reject) {
    
    
            reject("may");
        })
    } catch (e) {
    
    
        console.log(e);
    }
}
testA();

// 返回正常值
async function test(){
    
    
    let t = await new Promise(function (resolve, reject) {
    
    
        resolve("day");
    })
    console.log(t);
}
test();

Guess you like

Origin blog.csdn.net/LvJzzZ/article/details/109264225