Function
filter (promises, filterFn, label) Promise public
Defined in node_modules/rsvp/lib/rsvp/filter.js:42
import { filter } from 'rsvp';
- promises
- Array
- filterFn
- Function
- function to be called on each resolved value to filter the final results.
- label
- String
optional string describing the promise. Useful for tooling.
- returns
- Promise
filter
is similar to JavaScript's native filter
method.
filterFn
is eagerly called meaning that as soon as any promise
resolves its value will be passed to filterFn
. filter
returns
a promise that will become fulfilled with the result of running
filterFn
on the values the promises become fulfilled with.
For example:
import { filter, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [promise1, promise2, promise3];
let filterFn = function(item){
return item > 1;
};
filter(promises, filterFn).then(function(result){
// result is [ 2, 3 ]
});
If any of the promises
given to filter
are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
import { filter, reject, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error('2'));
let promise3 = reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let filterFn = function(item){
return item > 1;
};
filter(promises, filterFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
filter
will also wait for any promises returned from filterFn
.
For instance, you may want to fetch a list of users then return a subset
of those users based on some asynchronous operation:
import { filter, resolve } from 'rsvp';
let alice = { name: 'alice' };
let bob = { name: 'bob' };
let users = [ alice, bob ];
let promises = users.map(function(user){
return resolve(user);
});
let filterFn = function(user){
// Here, Alice has permissions to create a blog post, but Bob does not.
return getPrivilegesForUser(user).then(function(privs){
return privs.can_create_blog_post === true;
});
};
filter(promises, filterFn).then(function(users){
// true, because the server told us only Alice can create a blog post.
users.length === 1;
// false, because Alice is the only user present in `users`
users[0] === bob;
});