asynchronous or promised condition for array filter

后端 未结 1 542
终归单人心
终归单人心 2020-12-10 21:21

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

return someList.filter(function(element){ 
   //this part unfortunat         


        
相关标签:
1条回答
  • 2020-12-10 21:59

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

    With Bluebird:

      Promise.filter(someList,condition);
    

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

    0 讨论(0)
提交回复
热议问题