【问题标题】:Filtering undefined promises with BlueBird + React Native使用 BlueBird + React Native 过滤未定义的 promise
【发布时间】:2016-03-20 05:09:48
【问题描述】:

我正在尝试获取多个 rss 提要,获取它们的每个承诺,并使用 bluebird 合并每个返回的承诺的数组,以便为​​用户获取相关内容的数组。

但是,有时某些 RSS 提要已关闭或没有图像,并且这些承诺返回一个未定义的数组应该如下所示的位置:

所以我正在寻找一种方法来过滤掉这些不好的承诺并保留好的承诺。我对蓝鸟和一般承诺非常陌生,希望能提供任何帮助。这是我现在的代码(根本不会过滤掉任何 Promise,但会合并它们的数组):

//combining promises
    var that = this; 
    return Promise.all(rss_feeds)
      .then((res) => {
          for (var q = 0; q < res.length; q++)
          {
            for (var a =0; a < res[q].length; a++)
            {
              final_array.push(res[q][a]);
            }
          }
          //console.log('The following array of objects was constructed and is now being shuffled');
          //console.log(final_array.length);
          that.shuffle(final_array);
          //console.log(final_array);
          return final_array;
      }); 

【问题讨论】:

    标签: javascript arrays rss promise bluebird


    【解决方案1】:

    一旦一个值被包裹在Promise 中,检查它的唯一方法就是使用.then 方法。事实上,promise 之所以如此强大,是因为.then 允许在不关心其实际存在的情况下操作包装的值。换句话说,promise 代表了最终值的计算上下文。

    因此,您首先需要从一个 Promise 数组转移到一个带有 Promise#all 的数组 Promise,然后对最终的值数组进行推理(其中一些可能是 undefined)。之后,您可以过滤并返回仅包含所需值的新承诺。

    这导致:

    // dummy values to simulate the use case
    var arrayOfPromises = [Promise.resolve(1), Promise.resolve(undefined), Promise.resolve(2)]
    
    var result = Promise.all(arrayOfPromises).then(ps => ps.filter(p => p));
    result.then(console.log.bind(console));  // output: [1, 2]
    

    请注意,Bluebird 提供了一个额外的 Promise#filter 方法作为简写。但是,上面的代码具有使用 bluebird 和原生 ES6 Promise 的优势。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 2019-09-23
      • 2021-09-15
      • 2016-09-26
      • 2022-01-21
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多