用nodejs获取文件内容的方法来区分callback和Promise之间的区别
先创建src文件夹,src里面创建files文件夹和index.js文件。 files文件夹里面分别创建a.json,b.json,c.json。我是怕自己忘记,做的笔记没有做注释看不懂就算了,我自己看懂就可以了 a.json
{
"next": "b.json",
"msg": "this is a.json"
}
b.json
{
"next": "c.json",
"msg": "this is b.json"
}
c.json
{
"next": "null",
"msg": "this is c.json"
}
index.js callback方式
const fs = require('fs');
const path = require('path');
// callback 方式获取一个文件的内容
function getFileContent(fileName, callback) {
const fullFileName = path.resolve(__dirname, 'files', fileName)
fs.readFile(fullFileName, (err, data) => {
if (err) {
console.log(err)
return
}
callback(
JSON.parse(data.toString())
)
})
}// 测试 callback 回调地狱
getFileContent('a.json', aData => {
console.log('a.json', aData)
getFileContent(aData.next, bData => {
console.log('b.json', bData)
getFileContent(bData.next, cData => {
console.log('c.json', cData)
})
})
})
index.js 用promise方式
const fs = require('fs');
const path = require('path');
// 用promise 获取文件内容
function getFileContent(fileName) {
const fullFileName = path.resolve(__dirname, 'files', fileName)
const promise = new Promise((resolve, reject) => {
fs.readFile(fullFileName, (err, data) => {
if (err) {
reject(err)
return
}
resolve(
JSON.parse(data.toString())
)
})
})
return promise
}
getFileContent('a.json').then(aData => {
console.log('a.json', aData)
return getFileContent(aData.next)
}).then(bData => {
console.log('b.json', bData)
return getFileContent(bData.next)
}).then(cData => {
console.log('c.json', cData)
})
推荐阅读
- Docker应用:容器间通信与Mariadb数据库主从复制
- JS中的各种宽高度定义及其应用
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- 涉毒患者(新诗)
- 参保人员因患病来不及到指定的医疗机构就医,能否报销医疗费用()
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。