Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - asynchronous or promised condition for array filter

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?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...