我正在寻找类似的东西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
's),但我觉得这是错误的做事方式。它还消除了我使用抛出错误的能力。
有效,但感觉像是对 resolve 的错误使用
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 回答谢谢。