在 promise 中控制 this 的值

Controlling the value of this in a promise

我包装了 XMLHttpRequest 的一些功能。我将延迟的决议附加到触发的事件 onload。 IIUC XMLHttpRequestXMLHttpRequest 调用的回调中设置 this 的值以包含响应详细信息(响应文本、状态代码等)。

但我正在使用 q 并且 this 的值在延迟的解析中丢失了。如何确保将响应详细信息传播到使用 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;
}

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 本身。

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

cannot fulfill a promise with multiple values - 您尝试使用 apply 是徒劳的。如果您希望您的回调需要访问所有详细信息,您应该使用完整的 request 对象而不是它的 .result 仅解决承诺。