How do you loop through an asynchronous method in nodejs?

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?.


your problem is that you use index = perPageFiles.length-1 to judge that the task has been executed, but this judgment can only indicate that the last initiated readFile has ended. Because of asynchronism, the last initiated readFile is not necessarily the last to end, which does not mean that all readFile have been executed.

can be modified as follows, with an extra counter

  

generally speaking, it is best to read files asynchronously. For the simple requirement of the subject, you might as well package the step of reading files as promise, traversing all the file paths under the demand path, and the wrapper function before calling will return promise into an array, and then use the promise.all method to read all files at the same time.

Menu