javascript - Bluebird promise 库 : are . map 和 .filter 并行运行?

标签 javascript performance node.js parallel-processing bluebird

我试图在 bluebird promises 中编写一堆异步 fs 调用.除了我担心性能外,一切都很好。我不知道 .map.filter 函数是并行执行还是顺序执行。这是我的代码:

var Promise = require('bluebird'),
  fs = Promise.promisifyAll(require('fs'));

module.exports = getDirListing;

function getDirListing(path) {
  function toFullPath(file) {
    return path + file;
  }
  function onlyDirs(file) {
    return fs.statAsync(file).then(function(file) {
      return !file.isFile();
    });
  }
  function ignoreHidden(name) {
    return !(name.substring(0,1) === '.');
  }
  function toModuleNames(dir) {
    return dir.replace(path, '');
  }
  return fs.readdirAsync(path)
    .map(toFullPath)
    .filter(onlyDirs)
    .map(toModuleNames)
    .filter(ignoreHidden);
}

我特别关心对 onlyDirs 的调用,因为它会进行一堆异步 fs.stat 调用,并且可以/应该并行进行。我试着看 their api docs但我没有看到任何关于并行化的信息。

注意:我目前无法使用 ECMAScript6 生成器(不幸的是)。

此外,欢迎提出任何其他关于性能的建议。

最佳答案

fs.stat 调用是同时完成的,您可以通过以下方式验证:

var id = 0;
function onlyDirs(file) {
  var d = id++;
  return fs.statAsync(file).then(function(file) {
    console.log("returned from stat call %d", d);
    return !file.isFile();
  });
}
returned from stat call 0
returned from stat call 1
returned from stat call 2
returned from stat call 3
returned from stat call 5
returned from stat call 4
returned from stat call 6
returned from stat call 7
returned from stat call 8
returned from stat call 10
returned from stat call 11
returned from stat call 14
returned from stat call 13
returned from stat call 9
returned from stat call 15
returned from stat call 18
returned from stat call 17
returned from stat call 16
returned from stat call 12

请注意,代码最初不起作用,我不得不修改它:

var Path = require("path");
function toFullPath(file) {
    return Path.join(path, file);
}

关于javascript - Bluebird promise 库 : are . map 和 .filter 并行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22100101/

相关文章:

performance - MongoDB 性能。嵌入式文档搜索速度

javascript - 如何在javascript中使用正则表达式进行分割?

javascript - Node.js (Express API) : req. body.myobject 未定义且无法工作

performance - 慢 Scala 断言

javascript - 主文件从 Node.js 中的工作进程运行多次

javascript - 访问app.js中的io对象

javascript - Angular 4 index.html不会加载任何脚本

javascript - 在 vue 项目中运行 npm run serve 时出现问题

javascript - 您可以通过脚本确定 Chrome 是否处于隐身模式吗?

android - 尝试在空对象引用上调用虚拟方法 'void android.graphics.Bitmap.copyPixelsFromBuffer(java.nio.Buffer)'