所以我一直在考虑将XHR包装在Promise中。我遇到的问题是管理它们。有没有办法可以在Promise的 .then()中管理请求,而不是在Promise本身内部?
var i = 0;
var requests = [];
while(i < 10) {
mkPromise().then(function (response) {
console.log(response) // handle fulfilled requests
})
.catch(function (error) {
console.log(error)
})
.then(function (response) {
console.log(requests) // manage requests here
});
i++
}
function mkPromise () {
var url = 'http://example.com';
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
// Do this in the final .then() instead of here so that it's managed for errors as well without duplicating removal process
var index = requests.indexOf(req);
requests.splice(index,1)
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
requests.push(req)
// Make the request
req.send();
});
}