【问题标题】:Controlling the value of this in a promise在 promise 中控制 this 的值
【发布时间】:2015-02-26 22:22:01
【问题描述】:

我正在包装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;
}

【问题讨论】:

标签: javascript promise q


【解决方案1】:

this 的值在延迟分辨率的某处丢失。

The spec 要求在没有任何 this 值的情况下调用承诺回调。这就是为什么resolvereject 甚至不接受它的参数。如果一个回调想要使用一些this,它需要take care of that本身。

我如何确保响应的详细信息传播到注册了 promise 的回调中?

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

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 2018-11-25
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多