← Back To API Reference

Promise.filter

Promise.filter(
    Iterable<any>|Promise<Iterable<any>> input,
    function(any item, int index, int length) filterer,
    [Object {concurrency: int=Infinity} options]
) -> Promise

给定一个Iterable(数组是Iterable),或者一个可迭代的 promise,它产生 promise(或 promise 和值的混合),迭代遍历 Iterable 中所有的值放入一个数组中,并使用给定的 filterer 函数将过滤数组到另一个数组

它本质上是 .map并随后进行 Array#filter 的高效的快捷方式:

Promise.map(valuesToBeFiltered, function(value, index, length) {
    return Promise.all([filterer(value, index, length), value]);
}).then(function(values) {
    return values.filter(function(stuff) {
        return stuff[0] == true
    }).map(function(stuff) {
        return stuff[1];
    });
});

用于过滤当前目录中可访问目录的文件:

var Promise = require("bluebird");
var E = require("core-error-predicates");
var fs = Promise.promisifyAll(require("fs"));

fs.readdirAsync(process.cwd()).filter(function(fileName) {
    return fs.statAsync(fileName)
        .then(function(stat) {
            return stat.isDirectory();
        })
        .catch(E.FileAccessError, function() {
            return false;
        });
}).each(function(directoryName) {
    console.log(directoryName, " is an accessible directory");
});

Filter 选项: concurrency

参见 Map 选项: concurrency