TIMEX
TIMEX

Reputation: 271794

How do I filter out null values in my Promise.all result?

exports.getMentionedUsers = function(str) {
    return Promise.all(getUsernamesFromString(str).map(username => {
        return db.ref('/users').orderByChild('username').equalTo(username).once('value').then(snapshot => {
            return snapshot.val();
        });
    }));
}

Right now, if snapshot.val() is null, the element is still included in the final result.

How do I not insert a null element in the final map?

Upvotes: 7

Views: 3317

Answers (1)

alexmac
alexmac

Reputation: 19607

Add then callback and use Array#filter to remove null elements:

exports.getMentionedUsers = function(str) {
    return Promise
        .all(getUsernamesFromString(str).map(username => {
            return db.ref('/users').orderByChild('username').equalTo(username).once('value').then(snapshot => {
              return snapshot.val();
            });
        }))
        .then(values => values.filter(v => v);
}

Update: If you need to delete elements exactly with null value, you should use this filter: v => v !== null.

Upvotes: 8

Related Questions