javascript - 数组过滤器的异步或 promise 条件

标签 javascript arrays asynchronous promise q

我需要根据只能异步检查的条件过滤数组。

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/

相关文章:

javascript - HTML 选择下拉列表如何显示 VALUE/ID 而不是文本

javascript - Javascript 控制台中的 TypeError

java - php 的 array_multisort 函数相当于 java 中的函数

python - 如何成对合并多个数组

javascript - 为什么 console.log 在 promise 循环后工作

Flutter - Mockito - 在测试中使用 async 会产生错误,但使用 async* 可以正常工作吗?

javascript - 为什么 javascript 显示 "Uncaught SyntaxError: Identifier ' Common' has already been declared after making javascript class object"in console?

javascript - 使用咖啡 CLI,我如何将变量分配给所需的文件?

javascript - 在对象的子数组中搜索 - JavaScript

c# - 任务等待困惑