node中Promise使用实例
需求:现有三个文件需要依次读取文件内容
// a.json
{
"next": "b.json",
"massage": "this is a file content"
}
b.json
{
"next": "c.json",
"massage": "this b file content"
}
c.json
{
"next": "null",
"massage": "this c file content"
}
目录结构:

实现方法如下:
// 方法一: callback获去文件的内容
const fs = require("fs")
const path = require("path")
// 定义一个函数去获取文件内容
function getFileContent(fileName, callback) {
const fullFilename = path.resolve(__dirname, "files", fileName)
fs.readFile(fullFilename, (err, data) => {
if(err){
console.error(err)
return
}
// 调用callback函数处理读取到的数据
callback(
// readFile中读取的文件内容为buffer因此需要转为字符串
JSON.parse(data.toString())
)
})
}
getFileContent("

本文介绍了在Node.js环境中如何使用Promise处理异步操作,特别是针对依次读取多个文件内容的需求。通过示例展示了使用async/await的注意事项,包括await只能在async函数内使用,且await后面接promise,async函数返回promise,以及try-catch用于捕获reject错误。
最低0.47元/天 解锁文章
371

被折叠的 条评论
为什么被折叠?



