数组过滤器的异步或承诺条件 [英] asynchronous or promised condition for array filter

查看:91
本文介绍了数组过滤器的异步或承诺条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据只能异步检查的条件来过滤数组.

I need to filter an array based on a condition that can only be checked asynchronously.

return someList.filter(function(element){ 
   //this part unfortunately has to be asynchronous
})

有没有比我已经拥有的更好的兑现承诺的方法?

Is there any nicer way to do it with promises than what I already have?

此代码段使用 Q 来实现承诺,但实际上您可以假设任何适当的方法有望实现.

This snippet uses Q for promises, but you can actually assume any proper promises implementation.

return q.all(someList.map(function (listElement) {
        return promiseMeACondition(listElement.entryId).then(function (condition) {
            if (condition) {
                return q.fcall(function () {
                    return listElement;
                });
            } else {
                return q.fcall(function(){});
            }
        });
    }));

示例代码将promise解析为过滤后的数组,这是期望的结果.

The example code resolves the promise to a filtered array and that's the desired result.

推荐答案

在诸如Bluebird之类的库中,您内置了诸如.map.filter的promise之类的方法.您的方法通常是正确的.最后,您只是缺少Array.prototype.filter,从而消除了不良结果"-例如,使用BadValue常量解析并过滤与其相等的元素.

In libraries like Bluebird - you have methods like .map and .filter of promises built in. Your approach is generally correct. You're just missing an Array.prototype.filter at the end removing the "bad results" - for example, resolve with a BadValue constant and filter elements that are equal to it.

var BadValue = {};

return q.all(someList.map(function (listElement) {
        return promiseMeACondition(listElement.entryId).then(function (listElement) {
            return (condition(listElement)) ? listElement : BadValue;
    })).then(function(arr){
            return arr.filter(function(el){ return el !== BadValue; });
    });

使用蓝鸟:

  Promise.filter(someList,condition);

您当然可以将此功能提取到通用的filter函数中以作答.

You can of course, extract this functionality to a generic filter function for promises.

这篇关于数组过滤器的异步或承诺条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆