2

I'm trying to promisify the native XHR,

now here's the problem, when I use the following code:

function request(method, url) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = resolve;
        xhr.onerror = reject;
        xhr.send();
    });
}

it returns a promise instead of a XHR object,

so I cant use something like xhr.abort() in this way:

xhr = request('GET', 'http://google.com').then(function (e) 
{
    // ...code...
}, function (e)
{
    // ...code...
});

// When user press the stop button.
xhr.abort();

Is there anyway to make it returns a XHR object and still keep it promisable?

edit: This is not asking how to promisify a XHR object but how to make a "promisified" XHR object return the XHR object instead of the Promise.

Community
  • 1
  • 1
Yami Odymel
  • 1,782
  • 3
  • 22
  • 48
  • 2
    Related or duplicate of: http://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr – k0pernikus Apr 01 '16 at 09:27
  • An idea could be to inspire of AngularJS API :http://stackoverflow.com/questions/13928057/how-to-cancel-an-http-request-in-angularjs – pdem Apr 01 '16 at 09:48

1 Answers1

1

You would need to return a reference to the raw XHR or even the abort() method.

For example, return something like...

return {
   promise: promise,
   xhr: xhr
};

Then the calling code could use request().xhr.abort().

Obviously you will need to create these 2 variables, and create the XHR outside of the Promise callback.

If you really wanted it to work like you described, you could set the property on the Promise object, but it could be a confusing API.

alex
  • 479,566
  • 201
  • 878
  • 984