我正在尝试用蓝鸟承诺编写一堆异步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
调用,并且可以/应该并行。我尝试查看他们的 api 文档,但我没有看到任何关于并行化的内容。
注意:不幸的是,我目前无法使用 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);
}