javascript – 在所有内部并发承诺解决或拒绝后解析承诺

我正在寻找类似于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的承诺,这导致了预期的结果(结果数组和未定义的)但我觉得这是做错事情的方法.它还删除了我使用抛出错误的能力.

工作但感觉不正确使用决心

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答案谢谢.

最佳答案

I have succeeded in using Promise.all together with only ever resolving the fetchRequest promises

这基本上就是要走的路.在这种情况下,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};
    });
  }));
}

转载注明原文:javascript – 在所有内部并发承诺解决或拒绝后解析承诺 - 代码日志