先看看啥子是回调地狱
先建立一个test文件下面有files文件夹和index.js以及files下面有三个问价分别是a.json ,b.json,c.json 如下
a.json
b.json
c.json
index.js
const fs = require('fs')
const path = require('path')
callBack方式获取一个文件的内容
function getFileContent(fileName,callback){
// path.resolve把文件名 拼出来 _dirname是当前目录
const fullFileName=path.resolve(__dirname,'files',fileName)
fs.readFile(fullFileName,(err,data)=>{
if(err){
console.error(err)
return
}
callback(
// 将字符串的data 以对象的形式返回
JSON.parse(data.toString())
)
})
}
getFileContent('a.json',aData=>{
console.log('a aData:',aData)
getFileContent(aData.next,bData=>{
console.log('b bData:',bData)
getFileContent(bData.next,cData=>{
console.log('c cData:',cData)
})
})
})
上面的getFileContent中的callback就是一个回调函数,下面的调用他时会出现一层一层调用回调函数的情况,如果输出的文件不知这三个甚至更多的话会一直层层嵌套下去
用ES6的new Promise(function (resolve, reject){})解决回调地狱
代码:
function getFileContent(fileName) {
const promise = new Promise((resolve, reject) => {
const fullFileName = path.resolve(__dirname, 'files', fileName)
fs.readFile(fullFileName, (err, data) => {
// resolve 和reject都是函数
if (err) {
reject(err)
return
}
resolve(
// 将字符串的data 以对象的形式返回
JSON.parse(data.toString())
)
})
})
return promise
}
getFileContent ('a.json').then(aData=>{
console.log('a Data',aData)
// 怎么搞定bData,下面return了一个promise对象 所以又可以.then下去
// 所以只要一直返回promise对象就可以一直.then下去
return getFileContent(aData.next)
}).then(bData=>{
console.log('b Data',bData)
return getFileContent(bData.next)
}).then(cData=>{
console.log('c data',cData)
})
上面的创建了一个promise的对象 他会以两个函数作为参数分别是reject和resolve如果成功 就是reslove返回失败就reject报错
这里用到了promise对象的.then方法只要是promise就可以一直.then下去