我试图在 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/