What is callback hell? How to solve callback hell

1. What is callback hell?

	地狱这个词不陌生吧!对,没错就是那个十八层地狱的地狱,一层一层的地狱。

1. The difference between synchronous API and asynchronous API

This question needs to start from the Node.js API. Someone will ask here? Bloggers, didn’t you talk about the problem of callback hell? How can I get to the API, don’t worry, let the blogger explain to you step by step:

同步API 是从上到下依次执行,前面的代码会阻塞后面的代码执行
Please look at the following code


这里我写了一个for询还1000次,在循环里面打印,在循环体后面是另外的一个打印结果
结果是什么呢?
这个需要你自己去敲一下代码才能更好的了解喔!

for(var i=0; i<1000; i++){
    
    
	console.log(i);
}
console.log('循环体后面的代码')

异步API不会等待API执行完后在向下执行代码
Take a look at the following code, how will it be executed?

console.log('代码开始执行')
//异步操作 setTimout
setTimout(() =>{
    
     console.log('5秒后执行代码') },5000);//5000就是5秒
setTimout(() =>{
    
     console.log('0秒后执行代码')},0);
console.loh('代码结束执行');

这里的执行顺序是:
代码开始执行
代码结束执行
0秒后执行代码
5秒后执行代码

逻辑梳理:先执行同步的API,在去执行异步的API
      同步API有两个  分别是两个console.log
      异步API也有两个 分别是setTimout
      异步API里面的定时器会先执行0  在执行5

2. Asynchronous API in Node.js

	使用fs.readFile(‘./demo.txt’,(err,result) =>{});
	上面这个就是一个异步API
	是使用系统模块fs去查看文件

If the execution of the code behind the asynchronous API depends on the execution result of the current asynchronous API, but in fact the asynchronous API has not returned the result when the subsequent code is executed, how can this problem be solved?

	fs.readFile(‘./demo.txt’,(err,result) =>{});
	console.log('文件打印结果')

3. Write a case of callback hell caused by using asynchronous API

Case requirements:依次读取A文件,B文件,C文件

  1. First, you need to create a js file
  2. Then create 1.txt 2.txt 3.txt
  3. Write 1 2 3 in each text
  4. In this way, our 3 files are created, and we enter the link of code code.
const fs = require('fs')

fs.readFile('./1.txt','utf8',(err,result1) =>{
    
    
    console.log(result1);
    fs.readFile('./2.txt','utf8',(err,result2) =>{
    
    
        console.log(result2);

        fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
            console.log(result3);

        })
    })
});

Executing this js file, the execution result is correct, is it all right?
But we only wrote 3, what if we wrote 18

const fs = require('fs')

fs.readFile('./1.txt','utf8',(err,result1) =>{
    
    
    console.log(result1);
    fs.readFile('./2.txt','utf8',(err,result2) =>{
    
    
        console.log(result2);

        fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
            console.log(result3);
            fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                console.log(result3);
                fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                    console.log(result3);
                    fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                        console.log(result3);
                        fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                            console.log(result3);
                            fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                                console.log(result3);
                                fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                                    console.log(result3);
                                    fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                                        console.log(result3);
                                        fs.readFile('./3.txt','utf8',(err,result3) =>{
    
    
                                            console.log(result3);
                                
                                        })
                                    })
                                })
                            })
                        })
                    })
                })
            })
        })
    })
});

Can you understand this way? Such a layer of callbacks nested with a layer of callbacks, is it a bit like hell! Such code is not easy to maintain.

2. How to solve callback hell?

	Promise的出现就是解决Node.js异步编程中回调地狱的问题
基础语法
let promise = new Promise((resolve,reject) =>{
    
    
	setTimout(() =>{
    
    
	if(true){
    
    
	//resolve将异步API的执行结果传递出去
	    resolve({
    
    name:"张三"})
	}else{
    
    
		//reject 也是一个函数,当判断失败的时候,将结果传递出去
  		reject('失败了')
  }	
},2000);
})
//成功了
promise.then(result => console.log(result));//{name:‘张三’}
		.catch(error => console.log(error));//失败了

1. Use Promise to complete the case we did before

  1. Create a js file
  2. The file can just use the previous file
  3. Start code writing
//1、引入系统模块fS
const fs = require('fs');

//2、创建一个promise对象
let promise = new Promise((resolve,reject) =>{
    
    

    fs.readFile('./1.txt','utf8',(err,result) =>{
    
    
        if(err !=null){
    
    
            reject(err);
        }else{
    
    
            resolve(result);
        }
    });
});
//文件成功的信息
promise.then((result) =>{
    
    
    console.log(result);
})
//文件失败的信息
.catch((err) =>{
    
    
    console.log(err);
})

2. Improved method

const fs = require('fs')
function p1(){
    
    
    return new Promise((resolve,reject) =>{
    
    
        fs.readFile('./1.txt','utf8',(err,result) =>{
    
    
            resolve(result);
        })
    })
}
function p2(){
    
    
     return new Promise((resolve,reject) =>{
    
    
        fs.readFile('./2.txt','utf8',(err,result) =>{
    
    
            resolve(result);
        })
    })
}
function p3(){
    
    
    return new Promise((resolve,reject) =>{
    
    
        fs.readFile('./3.txt','utf8',(err,result) =>{
    
    
            resolve(result);
        })
    })
}
//依次执行1、2、3
p1().then((r1) =>{
    
    
    console.log(r1);
    //return p2
    return p2();
})
.then((r2) =>{
    
    
    console.log(r2);
    //return p3()
    return p3();
})
.then((r3) =>{
    
    
    console.log(r3);
})

After reading this, do you know what callback hell is? And how to solve it?
Remember! The memory of reading the code or reading the article is not deep. You have to type the code yourself. This often appears in the interview! The code word is not easy, I hope it can be triple connected with one key

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/115032044