javascript - How do I filter out null values in my Promise.all result? - Stack Overflow

exports.getMentionedUsers = function(str) {return Promise.all(getUsernamesFromString(str).map(username

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?

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?

Share Improve this question asked Aug 29, 2017 at 22:04 TIMEXTIMEX 272k367 gold badges802 silver badges1.1k bronze badges 3
  • if(snapshot.val()) return snapshot.val() – TimCodes Commented Aug 29, 2017 at 22:10
  • Use Array filter function and filter the null elements from your array – sidanmor Commented Aug 29, 2017 at 22:12
  • .then(arr => arr.filter(Boolean))? – Bergi Commented Aug 29, 2017 at 22:23
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742395532a4435866.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信