所有内部并发承诺解决或拒绝后,解决承诺

时间:2015-06-19 05:06:35

标签: javascript promise es6-promise

我正在寻找类似于Promise.all的东西,即使在一个或多个承诺拒绝或抛出错误的情况下,它也将继续同时解决承诺。每个请求都不依赖于其他请求。

接近我想要的 - 请参阅评论

function fetchRequest (request) {
  return new Promise(function (resolve, reject) {
    fetch(request)
    .then(function(response) {
      return response.text();      

    }).then(function (responseXML) {
      //Do something here. Maybe add data to dom
      resolve(responseXML);

    }).catch(function (err) {
      reject(new Error(err));
    }
}

function promiseRequests (requests) {
  var result = Promise.resolve();

  for (var i = 0; i < requests.length; i++) {
    result = fetchRequest(requests[i])
  }

  //This is wrong as it will resolve when the last promise in the requests array resolves
  // - not when all requests resolve
  resolve(result);
}

promiseRequests(['url1.com', 'url2.com']).then(function (data) {
  console.log('All requests finished');
  //optionally have data be an array of resolved and rejected promises
});

我成功地使用Promise.all并且只解决了fetchRequest的承诺,这导致了预期的结果(结果数组和undefined)但我觉得这是错误的做事的方式。它也消除了我使用抛出错误的能力。

工作但感觉不正确使用解决方法

function fetchRequest (request) {
  return new Promise(function (resolve, reject) {
    fetch(request)
    .then(function(response) {
      return response.text();      

    }).then(function (responseXML) {
      resolve(responseXML);

    }).catch(function (err) {
      resolve();
    }
}

Promise.all([fetchRequest('url1.com'), fetchRequest('url2.com')]).then(function (data) {
  console.log('All requests finished', data); //data could be ['resultXML', undefined]
});

请仅使用原生的es6 promise API答案谢谢。

2 个答案:

答案 0 :(得分:5)

  

我成功地使用Promise.all并且只解决了fetchRequest承诺

这基本上就是要走的路。在这种情况下,ES6没有像allSettled(Q)或settle(Bluebird 2.x)这样的辅助函数,所以我们需要像你一样使用Promise.all。 Bluebird甚至还有一个专用的.reflect()实用程序。

但是,如果拒绝,您将无法使用undefined解决问题,而是使用一些有用的值来识别错误。

function promiseRequests(requests) {
  return Promise.all(requests.map(request => {
    return fetch(request).then(res => {
      return {value:res};
    }, err => {
      return {reason:err};
    });
  }));
}

答案 1 :(得分:4)

你实质上是在想办法吞下任何错误。因此,这样的功能将是您最好的选择:

function swallow(p) {
  // transforms rejected promises into promises fulfilled with undefined
  return p.catch(function () { });
}

您可以按如下方式使用它:

Promise.all([swallow(fetch('url1.com')), swallow(fetch('url2.com'))]).then(function (data) {
  console.log('All requests finished', data); //data could be ['resultXML', undefined]
});

甚至

 const promises = ['url1.com', 'url2.com'].map(fetch).map(swallow);
 Promise.all(promises).then(function (data) {
   // ...
 });
相关问题