gpt4 book ai didi

javascript - 当一系列 readFile 调用在 node.js 中完成时如何运行函数?

转载 作者:行者123 更新时间:2023-12-03 04:18:08 24 4
gpt4 key购买 nike

在 node.js 中,我有一个循环遍历文件文件夹的模块。它实际上有一个函数回调,当它完成从目录的读取时会触发该函数回调。但是,对于它找到的每个文件,我运行一个 readFile 命令,该命令是异步函数,用于读取文件,并且也有一个回调函数。问题是,如何设置它以便在目录循环函数完成以及每个 readFile 函数完成后有回调?

var klaw = require('klaw');
var fse = require('fs-extra');

var items = [];

klaw("items").on('data', function (item) {
var dir = item.path.indexOf(".") == -1;
// if its a file
if (!dir) {
var filename = item.path;
if (filename.toLowerCase().endsWith(".json")) {
fse.readFile(filename, function(err, data) {
if (err) return console.error(err);
items.push(JSON.parse(data.toString()));
});
}
}
}).on('end', function () {

});

最佳答案

尝试这样的事情

    import Promise from 'Bluebird';

const processing = []
const items = [];

klaw("items")
.on('data', item => processing.push(
Promise.promisify(fs.readFile))(item.path)
.then(content => items.push(JSON.parse(content.toString())))
.catch(err => null)
)
.on('end', () => {
Promise.all(processing)
.then(nothing => console.log(items))
})

或者类似

const processing = []

klaw("items")
.on(
'data',
item => processing.push(Promise.promisify(fs.readFile)(item.path))
)
.on(
'end',
() => {
Promise.all(processing)
.then(contents => (
contents.map(content =>(JSON.parse(content.toString())))
)
.then(items => console.log(items))

})

关于javascript - 当一系列 readFile 调用在 node.js 中完成时如何运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44059207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com