0

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();
  });
}
Knight Yoshi
  • 924
  • 3
  • 11
  • 32
  • What do you mean by "manage"? – Bergi Feb 09 '16 at 19:39
  • I want to store the requests so that I can abort them if necessary (if the time takes too long) or otherwise look at the request in the promise – Knight Yoshi Feb 09 '16 at 19:42
  • Your `mkPromise` function should just bother with a single request. It should not need to know about that `requests` array at all. – Bergi Feb 09 '16 at 19:42
  • add parameters to `mkPromise()` to pass in config. urls, etc. you can also return an object containing the promise and other stuff, like the xhr object. i suppose you could tack properties onto the promise itself as well, if you didn't return it on the same line as it's created... – dandavis Feb 09 '16 at 19:42
  • 1
    If you want to make the request abortable, you must return more than a promise. – Bergi Feb 09 '16 at 19:43
  • Right, I don't want to deal with the requests array in the request itself, I want to do that in the promise's .then() – Knight Yoshi Feb 09 '16 at 19:44
  • @Bergi, using a [cancellation token principle](http://stackoverflow.com/questions/32897385/abort-ecmascript7-async-function/32897819#32897819), this could be handled with something passed-in rather than something returned. – spender Feb 09 '16 at 20:00

0 Answers0