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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…