回调地狱
Callback Hell
参考:https://www.jianshu.com/p/d31d2ecb4162
JS异步编程或使用大量回调函数时,使得代码不直观
什么是回调函数
downloadPhoto('一个URL', handlePhoto)
function handlePhoto (error, photo) {
if (error) console.error('Download error!', error)
else console.log('Download finished', photo)
}
console.log('Download started')
handlePhoto就是一个回调函数
多层的回调就形成Callback Hell
怎么解决回调地狱
1.让代码变得扁薄
给匿名函数起名 效果:
-
增强可读性
-
根据函数名来追踪代码执行过程,而不是看到一堆anonymous
-
同时也允许在别处声明函数,并通过函数名来引用它们
2.模块化代码
3.处理每一个单独的报错
使用回调函数来处理报错是最流行的方式
将错误信息作为第一参数传入回调函数
var fs = require('fs')
fs.readFile('FileUrl', handleFile)
function handleFile (error, file) {
if (error) return console.error('Uhoh, there was an error', error)
// otherwise, continue on and use `file` in your code
}