Basic usage of ES6-Promise, basic usage of async and await

Basic usage of ES6-Promise

1. Callback hell

  • Callback hell: Because js is single-threaded, sometimes functions need to be nested for code functional requirements. When functions are nested for multiple layers, callback hell will be formed
//里面函数嵌套函数时
function fun() {
    
    
            setTimeout(function() {
    
    
                console.log(2);
                setTimeout(function() {
    
    
                    console.log(1);
                    setTimeout(function() {
    
    
                        console.log(3);
                    })
                })

            })
        }

Solve the callback hell through the Promise method

2. What is Promise

Promise() is an object:
it has three forms:
1. pending
2. resolve successfully executed
3. reject failed to execute

  • When the state changes, the intelligence is converted from pending to resolve or from pending to reject; if it is in pending state, it is never known what state it will convert to next
  • Promise() receives a function as a parameter; the function has two parameters (the two parameters are natively provided by js), one is resolve and the other is reject

Promise() execution mechanism:

If Promise() is executed successfully, resolve() will be called; the parameter in resolve() is the result of successful execution, which is accepted by then(), then() is a function, and the parameter of the function is passed through resolve. The data

If Promise() fails to execute, it will call reject(); the parameter in reject() is the error message of execution failure, which is accepted by catch(), and the parameter of catch is a function. The parameter err of the function is the error message passed by reject

3. Use Promise to solve the above 1 function nesting problem

 //  使用Promise() 解决
        function fun1() {
    
    
        //1.先创建一个promise对象
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    //  then()
                    console.log('输出1');
                    //2.resolve 输出成功的状态
                    resolve()
                }, 1000)
            })
        }
        function fun2() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    //  then()
                    console.log('输出2');
                    resolve()
                }, 2000)
            })
        }
        function fun3() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(function () {
    
    
                    console.log('setTimeout3');
                    resolve();
                }, 2000)
            })
        }
         //通过then先调用fun2,再把fun2的结果返回,给fun1用,在把fun1的结果返回给fun3用   所以输出的结果为  2 3 1
        //  链式写法 
        fun2().then(fun1).then(fun3).then(() => {
    
    
            console.log('promise 执行全部结束');
        })

Insert picture description here

try-catch statement in js

The format is:

第一种写法:
	try{
    
    
		//测试的代码
	}catch{
    
    
		//代码的异常捕获(错误提示)
	}
第二种写法:
	try{
    
    
		//测试的代码
	}catch(err){
    
    
		//代码的异常捕获(错误提示)
	}

catch后面还有一个语句
	try{
    
    
            // 代码测试
        }catch{
    
    
            // 异常捕获 
        }finally{
    
    
            // finally 使用较少
           // 无论代码是否出错,此处的代码始终执行 
        }

[Note] If you need to output error information, catch must be followed by () and you need to pass in a parameter err (that is, error information), if you do not need to output error information, you do not need to follow () after catch

Insert picture description here

Promise's all method

When there are multiple Ajax requests, how to judge whether the multiple requests are finished?
Promise.all method can solve this problem

 <script>
        function fun1() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    console.log("setTimeout1");
                    resolve("setTimeout1执行成功")
                        // reject("1执行失败")
                }, 1000)
            })
        }

        function fun2() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    console.log("setTimeout2");
                    resolve("setTimeout2执行成功")
                        // reject("2执行失败")
                }, 1500)
            })
        }

        function fun3() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    console.log("setTimeout3");
                    resolve("setTimeout3执行成功")
                        // reject("1执行失败")
                }, 2000)
            })
        }
        const c = Promise.all([fun1(), fun2(), fun3()]);
        console.log(c);
        c.then((data) => {
    
    
            console.log(data);
        }).catch((err) => {
    
    
            console.log(err);
        })
    </script>
  • The Promise.all() parameter is an array, and each value in the array is an instance of Ppromise().

  • In the above case, the state of c is determined by fun1(), fun2(), fun3(), only fun1(), fun2(), fun3() are all successful, then the state of p is fulfilled (resolve); if fun1 (), fun2(), fun3() If there is a failure, the status of c is rejected

  • The parameter of the callback function of the then() method is the data passed when all Promise() instances are executed successfully, and all the data is automatically put into an array
    Insert picture description here
    Insert picture description here

Promise's race method

The parameter of the Promise.race() method is an array, each value in the array is a Promise() instance object; finally a new Promise() object is returned

Status changes: fun1(), fun2(), fun3() If the status of the three instance objects changes first (regardless of success or failure), the status of p will change accordingly. If fun1(), fun2(), fun3() ) The first state of the three instance objects changed is success, then success, if failure, then failure

//	1的状态是失败的,所以都是失败
 function fun1() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    console.log('setTimeout1');
                    // resolve('setTimeout1 的 data');
                    reject('setTimeout1 第一个失败');
                }, 1000)
            })
        }

        function fun2() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    console.log('setTimeout2');
                    resolve('setTimeout2 的 data2');
                    // reject('setTimeout2 的 失败');
                }, 1500)
            })
        }

        function fun3() {
    
    
            return new Promise((resolve, reject) => {
    
    
                setTimeout(() => {
    
    
                    console.log('setTimeout3');
                    resolve('setTimeout3 的 data3');
                    // reject('setTimeout3 失败了');
                }, 2000)
            })
        }
        //  Promise.race() 方法 的参数是一个数组, 数组中的每个值是 Promise() 实例对象; 最后返回一个新的Promise() 对象
        //  状态 改变: fun1(), fun2(), fun3() 三个实例对象 谁的状态先改变(不管成功还是失败),则p的状态都会随之跟随改变   如果fun1(), fun2(), fun3() 三个实例对象 先改变的状态是成功,则成功,如果失败则失败
        //  
        const p = Promise.race([fun1(), fun2(), fun3()]);
        p.then(res => {
    
    
            console.log(res);
        }).catch(err => {
    
    
            console.log(err);

        })

Basic usage of async and await

Callback hell: Solved by Promise()

Promise() to solve the callback hell will create a new problem: it is the chain call problem of Promise()

What is async

The async function is an asynchronous operation and returns a Promise() object

await wait; usually used in async function after await is a Promise() object, if not, it will be automatically converted to Promise() object form
Promise.resolve(100) to pass the data out

The combination of async and await can display asynchronous operations in a synchronous form

   async function fun() {
    
    
            console.log(1);
            //await后面 可以是一个函数,也可以是一个具体的值,也可以是promise对象
            let res = await fun2();
            await fun3()
            let res2 = await 2000;
            let res3 = await new Promise(function(resolve, reject) {
    
    
                resolve('这是Promise对象')
            })
            return "hello" + res + res2 + res3;
        }
        async function fun2() {
    
    
            console.log(2);
            return "world"
        }
        async function fun3() {
    
    
            console.log(3);
            return "四大方法法国"
        }
        fun().then(res => {
    
    
            console.log(res);
        });

Guess you like

Origin blog.csdn.net/weixin_53125457/article/details/114837212