So I've been looking into wrapping XHRs in a Promise. The issue I'm having is managing them. Is there a way I can manage the request in the Promise's .then(), instead of inside the body of the Promise itself?
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();
});
}