我正在包装XMLHttpRequest
的部分功能。我将延期决议附加到被解雇的事件onload
。 IIUC XMLHttpRequest
在this
调用的回调中设置XMLHttpRequest
的值,以包含响应详细信息(响应文本,状态代码等)。
但我使用的是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;
}
答案 0 :(得分:1)
this
的值在延迟的分辨率中丢失了。
The spec要求在没有任何this
值的情况下调用promise回调。这就是resolve
和reject
甚至不接受参数的原因。如果回调想要使用某些this
,则需要take care of that本身。
如何确保将响应详细信息传播到使用promise进行重新注册的回调?
您cannot fulfill a promise with multiple values - 您尝试使用apply
是徒劳的。如果您希望回调需要访问所有详细信息,则应使用完整的request
对象而不是.result
来解决承诺。