Promise.filter
Promise.filter(
Iterable<any>|Promise<Iterable<any>> input,
function(any item, int index, int length) filterer,
[Object {concurrency: int=Infinity} options]
) -> Promise
Given an Iterable
(arrays are Iterable
), or a promise of an Iterable
, which produces promises (or a mix of promises and values), iterate over all the values in the Iterable
into an array and filter the array to another using the given filterer
function.
It is essentially an efficient shortcut for doing a .map
and then 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];
});
});
Example for filtering files that are accessible directories in the current directory:
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");
});