perPageFiles = filenames.slice(articleIndex, articleIndex + perPage);
perPageFiles.forEach(function(filename, index) {
fs.readFile(fileDirectory + filename + ".md", "utf-8", function(err, data) {
if (err) throw err;
perPageDatas[index].articleContent = data.split("<!--more-->")[0];
if (index === perPageFiles.length - 1) {
result.count = totalArticles;
result.data = perPageDatas;
result.ret = true;
res.send(result);
}
});
});
this is a piece of code in my program that aims to use the readFile function to read files in a loop, but the test found that sometimes the read data will be lost. It seems that the data is because this method is asynchronous, can"t it be looped like this directly? can this be handled with promise or async?.