数组过滤器的异步或承诺条件

时间:2014-03-26 10:37:13

标签: javascript arrays asynchronous promise q

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

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

有没有比我已经拥有的承诺更好的方式呢?

此代码段使用Q作为承诺,但您实际上可以假设任何正确的承诺实现。

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(){});
            }
        });
    }));

示例代码解析了对已过滤数组的承诺,并且该结果符合预期结果。

1 个答案:

答案 0 :(得分:3)

在像Bluebird这样的图书馆中,您可以使用内置承诺的.map.filter等方法。您的方法通常是正确的。你最后错过了一个Array.prototype.filter,最后删除了'#34;糟糕的结果" - 例如,使用BadValue常量解析并过滤与其相等的元素。

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; });
    });

使用Bluebird:

  Promise.filter(someList,condition);

您当然可以将此功能提取到承诺的通用filter函数。