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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b2bb63-33e67.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b2bb63-33e67.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?