Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
993 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 Answer

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)
        })
    })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...