//读取文件的异步操作
const fs = require('fs');
const path = require('path')
// const fullFileName = path.resolve(__dirname, 'files','a.json')
// fs.readFile(fullFileName,(err,data)=>{
// if(err){
// console.log(err)
// return
// }
// console.log(data.toString())
// })
//不用promise,用普通的callback函数,获取一个文件的内容
function getFileContent(fileName,callback){
const fullFileName = path.resolve(__dirname, 'files',fileName)
fs.readFile(fullFileName,(err,data)=>{
//报错?
if(err){
console.log(err)
return
}
//没报错,执行callback
callback(
//文件都是json的
JSON.parse(data.toString())
)
})
}
//测试
//函数套函数,套了3层,callback回调函数
getFileContent('a.json', aData =>{
console.log('a data',aData)
getFileContent(aData.next, bData=>{
console.log('b data', bData)
getFileContent(bData.next, cData =>{
console.log('c data', cData)
})
})
})
//用promise,缓和一下,回调地狱。改平铺,看起来复杂,其实好用
function getFileContent(fileName){
const promise = new Promise((resolve,reject)=>{
const fullFileName = path.resolve(__dirname, 'files',fileName)
fs.readFile(fullFileName,(err,data)=>{
//失败执行reject函数
if(err){
reject(err)
return
}
//成功,执行resolve函数
resolve(
JSON.parse(data.toString())
)
})
})
return promise
}
//promise的测试
//通过next方法和.then拿到下一层数据
getFileContent('a.json').then(aData =>{
console.log('a data', aData)
return getFileContent(aData.next)
}).then(bData =>{
console.log('b data', bData)
return getFileContent(bData.next)
}).then(cData =>{
console.log('c data', cData)
})

