我需要根据只能异步检查的条件过滤数组。
return someList.filter(function(element){
//this part unfortunately has to be asynchronous
})
有没有比我现有的更好的方式来实现 promise ?
此代码段使用 Q对于 promise ,但您实际上可以假设任何适当的 promise 实现。
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 解析为经过过滤的数组,这就是所需的结果。
最佳答案
在像 Bluebird 这样的库中 - 你有内置的 promise 的 .map
和 .filter
方法。你的方法通常是正确的。您只是在最后缺少 Array.prototype.filter 来删除“不良结果” - 例如,使用 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);
您当然可以将此功能提取到用于 promise 的通用过滤器
函数中。
关于javascript - 数组过滤器的异步或 promise 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22658317/