使用promise进行多次异步调用,其中只有少数非常重要

时间:2016-09-21 17:33:32

标签: javascript node.js promise

我必须进行几次api调用才能获取数据以生成视图。假设有两个api调用,API1和API2。必须解析API1才能生成最小视图。如果API2也得到解决,我可以显示额外的功能。 我想同时进行两个调用并等待API1和API2使用

解析或拒绝
promise.all([getAPI1, getAPI2]).then(/*both successs*/).catch(/*any one fails*/)

但正如你所看到的,我这里只涉及两个场景而不是我想要的场景。即使API2失败,我也必须解决它。怎么做??

1 个答案:

答案 0 :(得分:1)

您可以这样做:

Promise.all([
  fetchSomething(),
  fetchSomethingElse().catch(error => {
    // fetchSomethingElse failed (it's ok)
    return null;
  })
]).then(results => {
  // results[1] will be null when fetchSomethingElse fails
}).catch(error => {
  // fetchSomething failed
});