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.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
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毫秒
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();
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');
This kind of task that does not block the execution of subsequent tasks is called an asynchronous task.
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)
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); })
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.
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());
You can see that when the async function returns data, it is automatically encapsulated into a Promise object.
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声明的函数是异步的');
当把flag设置为false是,执行结果为:async
关键字说完了,我们看看awai
关键字
//封装一个返回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();
结果为:
为什么叫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!