使用BlueBird + React Native

时间:2015-12-14 16:20:53

标签: javascript arrays rss promise bluebird

我正在尝试获取多个rss feed,获取他们的每个promise,并使用bluebird合并每个返回的promises的数组,以便为​​用户获取一系列相关内容。

但是,有时某些RSS源已关闭或没有图像,并且这些promise返回未定义,其中数组应如下所示:

enter image description here

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

//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;
      }); 

1 个答案:

答案 0 :(得分:2)

将值包含在Promise中后,检查它的唯一方法是使用.then方法。事实上,承诺如此强大的原因是.then允许操纵包裹的价值而不关心其实际存在。换句话说,promises代表最终值的计算上下文。

因此,您首先需要从承诺数组转移到具有Promise#all的数组的承诺,然后在最终值数组(其中一些可能是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承诺的优势。