What is es6 callback hell?

青灯夜游
Release: 2023-02-14 14:58:54
Original
1930 people have browsed it

In es6, callback hell is multi-layer callback functions nested in each other, that is, callback functions nested in callback functions; it is an operation that occurs to achieve sequential execution of code, and it will cause us The code is very poorly readable and difficult to maintain later. Promise is used in es6 to solve the problem of callback hell.

What is es6 callback hell?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

##Preface

Before we formally understand “callback hell”, we first understand two concepts:

1. Callback function

When a function is passed as a parameter to another parameter, and it will not be executed immediately, the function can only be executed when certain conditions are met. This kind of function is called Callback. There are callback functions in the timers and Ajax that we are familiar with:

setTimeout(function(){   //function(){console.log('执行了回调函数')}就是回调函数,它只有在3秒后才会执行
	console.log('执行了回调函数');
},3000)  //3000毫秒
Copy after login
The callback function here is

function(){console.log('The callback function was executed')}, in Execute after 3 seconds.

//1.创建异步对象
			var xhr=new XMLHttpRequest();
      //2.绑定监听事件(接收请求)
			xhr.onreadystatechange=function(){
				//此方法会被调用4次
				//最后一次,readyState==4
				//并且响应状态码为200时,才是我们要的响应结果 xhr.status==200
				if(xhr.readyState==4 && xhr.status==200){
					//把响应数据存储到变量result中
					var result=xhr.responseText;
					console.log(result);
				}
			}
      //3.打开链接(创建请求)
			xhr.open("get","/demo/ajaxDemo",true);
      //4.发送请求
			xhr.send();
Copy after login
The callback function here is the function bound to

xhr.onreadystatechange, which is executed after xhr.send() sends the request and gets the response.

2. Asynchronous tasks

The corresponding concept is "synchronous tasks". Synchronous tasks are queued for execution on the main thread, and only the previous task is executed. to perform the next task. Asynchronous tasks do not enter the main thread, but enter the asynchronous queue. Whether the previous task is completed does not affect the execution of the next task. Similarly, take the timer as an example of an asynchronous task:

setTimeout(function(){
    console.log('执行了回调函数');
},3000)
console.log('111');
Copy after login

If you follow the order in which the code is written, "callback function executed" should be output first, and then "111". But the actual output is:


What is es6 callback hell? This kind of task that does not block the execution of subsequent tasks is called an asynchronous task.

Next let’s take a look at what callback hell is.

1. What is callback hell?

Based on the above, we can draw a conclusion: there is a code for asynchronous tasks, which cannot be guaranteed to be executed in order. So what if we have to execute the code in order?

For example, if I want to say a sentence, the word order must be as follows: In martial arts, peace should be valued, martial ethics should be respected, and no fighting should be avoided.

I have to do this to ensure that the order is correct:

        setTimeout(function () {  //第一层
            console.log('武林要以和为贵');
            setTimeout(function () {  //第二程
                console.log('要讲武德');
                setTimeout(function () {   //第三层
                    console.log('不要搞窝里斗');
                }, 1000)
            }, 2000)
        }, 3000)
Copy after login

What is es6 callback hell?

You can see that the callback function in the code is nested in three layers. This situation of nesting callback functions within callback functions is called callback hell.

To summarize, callback hell is an operation that occurs to achieve sequential execution of code. It will cause our code to be very poorly readable and difficult to maintain later.

So how to solve callback hell?

2. How to solve callback hell

1.Promise

Promise is in js A native object is a solution for asynchronous programming that can replace the traditional callback function solution.

  • The Promise constructor receives a function as a parameter. The asynchronous task we need to process is unloaded in the function body. The two parameters of the function are resolve and reject. When the asynchronous task is successfully executed, the resolve function is called to return the result, otherwise reject is called.

  • The then method of the Promise object is used to receive the response data when the processing is successful, and the catch method is used to receive the corresponding data when the processing fails.

  • The chain programming of Promise can guarantee the execution order of the code. The premise is that every time after than is processed, a Promise object must be returned so that it can be received at the next then data.

The following is an example code:

        function fn(str){
            var p=new Promise(function(resolve,reject){
                //处理异步任务
                var flag=true;
                setTimeout(function(){
                    if(flag){
                        resolve(str)
                    }
                    else{
                        reject('操作失败')
                    }
                })
            })
            return p;
        }

        fn('武林要以和为贵')
        .then((data)=>{
            console.log(data);
            return fn('要讲武德');
        })
        .then((data)=>{
            console.log(data);
            return fn('不要搞窝里斗')
        })
        .then((data)=>{
            console.log(data);
        })
        .catch((data)=>{
            console.log(data);
        })
Copy after login

What is es6 callback hell? But the biggest problem with Promise is code redundancy. The original asynchronous task is encapsulated by Promise, regardless of Using than for all operations will result in everything being then...then...then... at first glance, which is not conducive to code maintenance.

So the following async/await code looks more like synchronous code.

2.async/await

First we look at the

async keyword, which is A keyword is placed in front of the declared function, indicating that the function is an asynchronous task and will not block the execution of subsequent functions:

        async function fn(){
            return '不讲武德';
        }
        console.log(fn());
Copy after login

What is es6 callback hell? You can see that when the async function returns data, it is automatically encapsulated into a Promise object.

Like the Promise object, when processing asynchronous tasks, you can also return different data according to success and failure. When the processing is successful, use the then method to receive it, and when it fails, use the catch method to receive the data:

        async function fn() {
            var flag = true;
            if (flag) {
                return '不讲武德';
            }
            else{
                throw '处理失败'
            }
        }
        fn()
        .then(data=>{
            console.log(data);
        })
        .catch(data=>{
            console.log(data);
        })

        console.log('先执行我,表明async声明的函数是异步的');
Copy after login

What is es6 callback hell?
当把flag设置为false是,执行结果为:
What is es6 callback hell?
async关键字说完了,我们看看awai关键字

  • await关键字只能在使用async定义的函数中使用
  • await后面可以直接跟一个 Promise实例对象(可以跟任何表达式,更多的是跟一个返回Promise对象的表达式)
  • await函数不能单独使用
  • await可以直接拿到Promise中resolve中的数据。
        //封装一个返回promise的异步任务
        function fn(str) {
            var p = new Promise(function (resolve, reject) {
                var flag = true;
                setTimeout(function () {
                    if (flag) {
                        resolve(str)
                    } else {
                        reject('处理失败')
                    }
                })
            })
            return p;
        }

        //封装一个执行上述异步任务的async函数
        async function test(){
            var res1=await fn('武林要以和为贵');  //await直接拿到fn()返回的promise的数据,并且赋值给res
            var res2=await fn('要讲武德');
            var res3=await fn('不要搞窝里斗');
            console.log(res1,res2,res3);
        }
        //执行函数
        test();
Copy after login

结果为:
What is es6 callback hell?
为什么叫await等待呢,因为当代码执行到async函数中的await时,代码就在此处等待不继续往下执行,知道await拿到Promise对象中resolve的数据,才继续往下执行,这样就保证了代码的执行顺序,而且使异步代码看起来更像同步代码。

总结

总结一下,当我们写代码遇到异步回调时,我们想让异步代码按照我们想要的顺序执行,如果按照传统的嵌套方式,就会出现回调地狱,这样的代码不利于维护,我们可以通过Promise对象进行链式编程来解决,这样尽管可以解决问题,但是ES7给我们提供了更加舒适的async/await语法糖,可以使得异步代码看起来更像是同步代码。

【相关推荐:javascript视频教程web前端

The above is the detailed content of What is es6 callback hell?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template