1

I am wrapping some of the functionality of XMLHttpRequest. I am attaching the resolution of a deferrred to the event fired onload. IIUC XMLHttpRequest sets the value of this in the callback invoked by XMLHttpRequest to contain the response details (response text, status code etc.).

But I am using q and the value of this is lost somewhere in the resolution of the deferred. How can I ensure the response details are propagated to the callback resgistered with the promise then?

XMLHttpRequestWrapper.prototype.get = function(url) {
    var deferred = q.defer();
    var request = new XMLHttpRequest();

    request.onload = function() {
        // this now contains the response info
        deferred.resolve.apply(this, arguments); // 'this' is lost in the internals of q :(
    };
    request.onerror = function() {
        deferred.reject.apply(this, arguments);
    };

    request.open('GET', url, true);
    request.send();

    return deferred.promise;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

1 Answers1

1

the value of this is lost somewhere in the resolution of the deferred.

The spec requires that promise callbacks are invoked without any this values. That's why resolve and reject don't even accept a parameter for it. If a callback wants to use some this, it needs to take care of that itself.

How can I ensure the response details are propagated to the callback resgistered with the promise then?

You cannot fulfill a promise with multiple values - your attempt to use apply is futile. If you expect your callbacks to need access to all details, you should resolve the promise with the complete request object instead of its .result only.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375