在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

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函數(shù)循環(huán)讀取文件,但是測試發(fā)現(xiàn)有時候讀取的數(shù)據(jù)會丟失,查了下資料貌似是因為這個方法是異步的,不能直接這樣循環(huán)么,這個能用promise或者async來處理么。。

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

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

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

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

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

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

可以作如下修改, 用額外的計數(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