How to use front-end async await

One topic that programmers cannot escape is the execution efficiency of the code. This is true for the backend and the frontend. Therefore, async/await asynchronous development is an important knowledge point for everyone to improve their code efficiency. This is true for Python and JS, so let’s talk about async/await asynchronous programming based on JS today.

asynchronous

Still, let’s talk about the basic concept first, asynchronous. Its antonym is synchronous. To investigate the root cause, we need to talk about processes and execution queues in computer principles. Simply put, we execute a function under normal circumstances. During the execution of the current function, if we encounter file content loading or waiting for a response, the program will enter a blocked state and will not immediately respond or continue to execute new tasks. Then send an email based on the front-end as an example:

(1) Request to send mail

(2) Email sending

(3) The page waits for the email to be sent

(4) The user waits for the page to respond

(5) The user is annoyed and starts to refresh the page to try again

(6) Repeat the above steps 2-3 times, the user will leave cursing or swearing

(7) Bad reviews

So based on the above description, we can see that blocking not only affects the efficiency of code execution, but also is very fatal to user experience. Then, there is the concept of asynchronous. The so-called asynchronous means that after the execution is initiated, the program enters the waiting state and does not enter the blocking state. Instead, it continues to execute the following functions until the result is returned after waiting, and then responds again. Obviously, it can avoid the above problems very well. Based on the front end, the asynchrony I first learned was ajax, asynchronous requests, and partial refresh of the page. At that time, I felt quite nice, but gradually found that ajax only asynchronously requests, and there is no good solution for functions that need asynchronous. In this case, there are async and await

async

As a keyword placed in front of the function, it means that this function is an asynchronous function, then the execution of this function will not block the execution of the following code, but the call of an asynchronous function is the same as that of a normal function, but the return result is different.

<script>
    async function say_hello() {
    
    
        return "hello world"
    }
    console.log(say_hello()); //Promise 对象
    console.log("hi man") //
</script>

It can be seen that after say_hello is converted into an asynchronous function, it does not directly return the result, but returns a Promise object. Through the debugging mode, we can see that there are several methods on the promise, which are a bit like a life cycle according to the meaning of the word. Let's call them one by one.

image.png

<script>
        async function say_hello(f) {
    
    
            if(f === 1){
    
    
                return "hello world";
            }else{
    
    
                throw new Error("这里要发生错误"); //引发错误
            }
        }
        say_hello().catch((args)=>{
    
    
            console.log("catch 被调用了");
            console.log(args);
            console.log("catch 被调用了");
        });
        say_hello().finally(()=>{
    
    
            console.log("finally 被调用了收尾");
        });
        say_hello().then((args)=>{
    
    
            console.log("then 被调用了");
            console.log(args);
            console.log("then 被调用了");
        });
        console.log(say_hello(1));
</script>

The constructor will be discussed in detail later, so the following three functions can be clearly seen to be executed in different states

method describe
catch There are parameters, which are executed when an error occurs in the asynchronous function, and the parameter receives the wrong content
then With parameters, it is executed after the asynchronous function is completed normally, and the parameter is the result returned by the asynchronous function
finally Execute after the execution of the error function is completed, if there is no action, execute before then

A more in-depth discussion is: the Promise object has a state. If the state of the Promise object becomes resolved, the thencallback function specified by the method is called; if the asynchronous function throws an error, the state becomes rejected, and the catchcallback function specified by the method is called to handle the error. And finally is a function used to end after an error, and it should be noted that: if the callback function specified by the then method throws an error during operation, it will also be captured by the catch method.

await

await is waiting, which is used to wait for a Promise object to execute (it's a bit of a coroutine). It can only be used in the async function. If it is not a promise object, the result of the await expression is what it is waiting for. If it waits for a promise object, await will be busy. It will block the following code, wait for the promise object to resolve, and then get the resolved value as the operation result of the await expression.

<script>
    async function say_hai(){
    
    
        return "hi world"
    }
    async function say_hello() {
    
    
        await say_hai().then((args)=>{
    
    
            console.log("hi man")
        }); //这里await右侧是一个异步函数,所以会阻塞程序,到这个异步函数执行完成之后,再往下执行
        return "hello world"
    }
    say_hello().then((args)=>{
    
    
        console.log("then 被调用了");
        console.log(args);
        console.log("then 被调用了");
    });
    console.log(say_hello());
</script>
<script>
    function say_hai(){
    
    
        return "hi world"
    }
    async function say_hello() {
    
    
        const res = await say_hai(); //这里await右侧是一个常规函数,所以await只是拿到了函数返回的结果
        console.log(res);
        return "hello world"
    }
    say_hello().then((args)=>{
    
    
       console.log("then 被调用了");
       console.log(args);
       console.log("then 被调用了");
    });
    console.log(say_hello());
</script>

Therefore, await is usually used to block the execution of another asynchronous function in an asynchronous function. If combined with production consumers, an asynchronous function produces and an asynchronous function consumes, using await to call consumption inside the production will produce one, call one, and switch back and forth between the production and the execution of the calling function, and the execution effect will be more synchronous.

But note:

The await keyword will block the subsequent code until the promise is completed, just like performing a synchronous operation, so it is inappropriate to use too many awaits, and each await will wait for the previous one to complete, then the meaning of using asynchronous functions will be lost.

Guess you like

Origin blog.csdn.net/weixin_45506717/article/details/131834352