js基础知识 —— 回调函数与回调地狱
一、回调函数
- 回调函数,本质上就是一个函数
- 一个函数A以实参的形式传递到函数B中,以形参的方式调用函数A,此时 函数A就可以称为函数B的回调函数,回调函数的使用场景为异步代码的解决方法
function A() {
console.log('函数A')
}
function B(callback) {
callback()
}
B(A)
function fn () {
const timer = Math.ceil(Math.random() * 3000)
setTimeout(() => {
if (timer > 2500){
console.log('网络超时',timer)
}else {
console.log('请求成功',timer)
}
},timer)
}
fn()
二、回调地狱
- 不是代码的漏洞,只是在利用回调函数解决问题时,代码量多了之后的一个视觉体验
- 回调地狱的代码不利于我们去维护或者管理, 所以后续再处理异步任务的时候,我们需要一些更加简洁的方法,此时出现了一个东西promise ,异步解决方案
function fn (cg,sb) {
const timer = Math.ceil(Math.random() * 3000)
console.log('班长买水')
setTimeout(() => {
if (timer > 500){
console.log('买水失败,用时',timer)
sb()
}else {
console.log('买水成功,用时',timer)
cg()
}
},timer)
}
fn(
() => {
fn(
() =>{console.log('买完水又买了一箱饮料')},
() =>{console.log('只买了水,没买饮料')}
)
},
() => {
fn(
() => {console.log('第二次买水成功')},
() => {
fn(
() => {console.log('第三次买水成功')},
() => {console.log('第三次买水失败,废物')}
)
}
)
}
)