鍍金池/ 問答/Linux  HTML/ nodejs中怎么循環(huán)執(zhí)行一個(gè)異步的方法呢?

nodejs中怎么循環(huán)執(zhí)行一個(gè)異步的方法呢?

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);
    }
  });
});

這個(gè)是我程序中的一段代碼,目的是利用readFile函數(shù)循環(huán)讀取文件,但是測(cè)試發(fā)現(xiàn)有時(shí)候讀取的數(shù)據(jù)會(huì)丟失,查了下資料貌似是因?yàn)檫@個(gè)方法是異步的,不能直接這樣循環(huán)么,這個(gè)能用promise或者async來處理么。。

回答
編輯回答
兮顏
這個(gè)能用promise或者async來處理么

可以,但是本來就提供了同步API的readFileSync。

2018年8月9日 15:39
編輯回答
小眼睛

一般來說讀取文件最好是使用異步讀取,對(duì)于題主這個(gè)簡(jiǎn)單的需求來說,不妨將讀取文件這一步包裝為promise ,遍歷需求路徑下的所有文件路徑,調(diào)用之前的包裝函數(shù)將返回promise都放到一個(gè)數(shù)組里面,然后在使用promise.all方法同時(shí)讀取所有的文件。

2017年6月3日 00:20
編輯回答
柒槿年

你的問題在于, 你用index === perPageFiles.length - 1判斷任務(wù)已經(jīng)執(zhí)行完畢, 但這個(gè)判斷只能說明最后一個(gè)發(fā)起的readFile已經(jīng)結(jié)束, 因?yàn)楫惒降年P(guān)系, 最后一個(gè)發(fā)起的readFile并不一定是最后一個(gè)結(jié)束的, 這并不能說明所有的readFile已經(jīng)執(zhí)行完畢.

可以作如下修改, 用額外的計(jì)數(shù)器

perPageFiles = filenames.slice(articleIndex, articleIndex + perPage);
let completedCount = 0;
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];
    completedCount++;
    if (completedCount === perPageFiles.length) {
      result.count = totalArticles;
      result.data = perPageDatas;
      result.ret = true;
      res.send(result);
    }
  });
});
2018年6月10日 00:43