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);
}
});
});
这个是我程序中的一段代码,目的是利用readFile函数循环读取文件,但是测试发现有时候读取的数据会丢失,查了下资料貌似是因为这个方法是异步的,不能直接这样循环么,这个能用promise或者async来处理么。。
你的问题在于, 你用
index === perPageFiles.length - 1
判断任务已经执行完毕, 但这个判断只能说明最后一个发起的readFile已经结束, 因为异步的关系, 最后一个发起的readFile并不一定是最后一个结束的, 这并不能说明所有的readFile已经执行完毕.可以作如下修改, 用额外的计数器