Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

async 读取文件

async function a() {
    var result = await b()
    res.json(result)
}
var fse = require('fs-extra')

function b() {
    var fpath = '/data.json'
    // 异步读取文件
    fse.readJson(fpath, (err, data) => {
        if(err) console.log(err)
        return data
    })
}

上述代码中, resultundefined,即并没有得到读取文件后的数据。我应该怎么修改,让result 得到 data.json 的内容呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

这种情况建议你使用stream 而且你的b函数并没有返回一个Promise 建议了解一下async/await和Promise之间的关系, 两种处理方法

1.

var data = fs.createReadStream('/data.json')
data.pipe(res)

2.

function b () {
    var fpath = '/data.json'
    return new Promise((resolve, reject) =>{
        readJson(fpath, (err, data) => {
            if (err) reject(err)
            resolve(data)
        })
    })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...