es8 asynchronous function async/await


Asynchronous function

async/await are two new function keywords added to ES8, allowing code written in a synchronous manner to be executed asynchronously

1. async

The async keyword is used to declare asynchronous functions. This keyword can be used before function declarations, function expressions, arrow functions and methods

    async function f() {
    
    
        return 1;
    }

If the asynchronous function returns a value with return (if there is no return, it will return undefined), this value will be automatically wrapped in a resolved Promise, and result is the value

    async function f() {
    
    
        return 1;
    }
    f().then(console.log); // 1

async ensures that the function returns a Promise and also wraps non-Promise values ​​in it

2. await

await only works in the async function. This keyword can suspend the execution of the asynchronous function code and wait for the Promise to be resolved.

    async function f() {
    
    

        let promise = new Promise((resolve, reject) => {
    
    
            setTimeout(() => resolve("done!"), 1000)
        });
        let p = await promise;  // 暂停
        console.log(p); // 一秒后 "done!";
    }
    f();

The function is paused in the await line until the value of p
is obtained when the promise settles and continues to execute. Compared with promise.then, it is just a more elegant syntax for obtaining the result of the promise, and it is also easier to read and write.
The above function can be rewritten as:

    let promise = new Promise((resolve,reject)=>{
    
    
        setTimeout(()=> resolve("done!"),1000)
    });
    promise.then(console.log);

ps. Await cannot be used in ordinary functions, and cannot be used in top-level contexts such as M <script>tags, but asynchronous functions can be defined and executed immediately

    (async function f(){
    
    
        console.log(await Promise.resolve(1));
    })();

To fully understand the await keyword, you must know that it is not just waiting for a value to be available. When the JavaScript runtime encounters the await keyword, it will record where the execution is suspended. When the value on the right of await is available, the JavaScript runtime will push a task to the message queue, and this task will resume the execution of the asynchronous function.

    async function foo() {
    
    
        console.log(2);
        await null;
        console.log(4);
    }
    console.log(1);
    foo();
    console.log(3);
    // 1
    // 2
    // 3
    // 4

Even if await is followed by an immediately available value, the later part of the function will be evaluated asynchronously

to sum up

An asynchronous function is the result of applying a contract to a JavaScript function. Asynchronous functions can suspend execution without blocking the main thread.

The keyword async before the function has two effects:

  1. This function always returns a promise.
  2. It is allowed to use await within this function.

The keyword await before the promise makes the JavaScript engine wait for the promise to settle, and then:

  1. If there is an error, an exception will be thrown—just like throw error was called there.
  2. Otherwise, the result is returned.

Guess you like

Origin blog.csdn.net/S_aitama/article/details/111146828