You need to master promise before you can learn async and await.

Objective:

Asynchronous programming, synchronous writing allows us to process asynchronous processes synchronously without blocking the main thread

Rules of Use:

  1. Any function that starts with async will automatically return a Promise object after execution
  2. Await must be used in async functions and cannot be used alone
  3. “Await” is followed by a promise object, otherwise it is meaningless. And a promise object after “await” does not need to write “then”, because one of the functions of “await” is to get the parameters passed by the success state of the following promise object.

Basic API:

  1. The async function returns a Promise object
   async function fn() {
            return await 1
   }
   console.log(fn())
Copy the code
  1. Async function f(){} await cannot be used independently of async, and await should normally appear inside an async function
  2. The return value inside the async function exists as the resolve parameter of the Promise object
   async function fn() {
       return await 1
   }

   fn().then(res => {
       console.log(1)
   }).catch(err => {
       console.log(err)
   })
Copy the code
  1. Await will make the current execution pause until the state becomes a pity or Rejected; An asynchronous operation await is typically a promise await what?

    1. We usually await an async function with await, but syntactically, await is an expression that evaluates to a Promise object or other value. Therefore, after await, we can actually receive ordinary function calls or direct quantities
    2. If an await waits for something other than a promise object, the result of the following expression is what it waits for; If it is a promise object, await will block the following code, and the promise object resolve will get the value of resolve as the result of an await expression although await blocks, await in async, async does not block, All of its internal blocking is wrapped in a Promise object and executed asynchronously

    Use ‘await’ in an async function, and the code in ‘await’ becomes synchronous. This means that the code will continue to wait until the Promise behind ‘await’ is completed. ‘await’ means to wait.

    function fn() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(1)
                }, 1000)
            })
        }

        async function test() {
            let p1 = await fn();
            console.log(p1)
            let p2 = await fn();
            console.log(p2)
            let p3 = await fn();
            console.log(p3)
        }
        test(a)Copy the code

Error handling:

Await can directly obtain the parameters passed by the subsequent Promise success state, but cannot capture the failure state. Here we solve the problem by adding then/catch methods to the async function wrapped with await, which itself returns a Promise object.

//1)try.... catch()...function p1() {
            return new Promise((resolve, reject) => {
                setTimeout(function() {
                    reject({
                        "error": 400
                    })
                }, 1000)
            })
        }

        async function fn() {
            try {
                let res = await p1()
            } catch (err) {
                console.log(err)
            }
        }
        fn()
Copy the code
/ / 2) catch function:function p2() {
            return new Promise((resolve, reject) => {
                setTimeout(function() {
                    reject({
                            error: 400
                        })
                        // resolve("1")
                }, 1000)
            })
        }


        async function fn() {
            let res = await p2().catch(err => {
                console.log(err)
            })
            console.log(res)
        }
        fn()
Copy the code

Concurrent processing

        let p1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("1")}, 1000)});let p2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve("2")}, 2000)}); asyncfunction fn(callback) {
            let res1 = await p1;
            let res2 = await p2;
            callback([res1, res2])
        }

        fn((data) => {
            console.log(data)
        })
Copy the code

Solve callback hell

    function timer(msg) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (msg == 2) reject("Failure");
                else resolve(msg);
            }, 1000);
        });
    }
    async function async_timer() {
        let t1 = await timer(1);
        console.log(t1);
        let t2 = await timer(2).catch(err => {
            console.log(err);
        });
        console.log(t2);
        let t3 = await timer(3);
        console.log(t3);
    }
    async_timer();
Copy the code