数组过滤器的异步或承诺条件 [英] 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
})
有没有比我已有的方法更好的使用 promise 的方法?
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
这样的内置承诺的方法.您的方法通常是正确的.您只是在最后缺少一个 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);
当然,您可以将此功能提取到用于 Promise 的通用 filter
函数.
You can of course, extract this functionality to a generic filter
function for promises.
这篇关于数组过滤器的异步或承诺条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!