1

Promise.all1 つ以上の約束が拒否またはエラーをスローした場合でも、約束を同時に解決し続けるようなものを探しています。各リクエストは別のリクエストに依存しません。

私が望むものに近い - コメントを見てください

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.allfetchRequest の約束を解決するだけで一緒に使用することに成功しました。これにより、期待される結果(結果と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 のみが回答してください。

4

2 に答える 2

6

約束をPromise.all解決するだけで一緒に使用することに成功しましたfetchRequest

それが基本的な方法です。allSettledこの場合、ES6 には(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};
    });
  }));
}
于 2015-06-19T05:17:39.030 に答える
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) {
   // ...
 });
于 2015-06-19T05:17:15.070 に答える