【发布时间】:2014-04-12 19:58:32
【问题描述】:
在代表请求的类中,我尝试使用 Q Promise 处理它,然后使用两个简单的处理程序来发送处理结果。为什么这不起作用:
Request.prototype.process = function() {
var that = this;
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(that.replyOK)
.fail(that.replyError);
};
但这确实:
Request.prototype.process = function() {
var that = this;
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(function(error) {
that.replyOK(error);
})
.fail(function(error) {
that.replyError(error);
});
};
【问题讨论】:
-
可能是因为您的
replyOK和replyError函数关心this在其体内的内容,这不像您认为在第一种情况下的使用那样受到约束,而在第二个。 -
你确定第二个例子中有
.then(...)和.fail(...)之前的分号吗? -
正如 Bray 所说,在第一种情况下,replyOK 和 replyError 中的 this 未在调用中设置,因此它将默认为全局对象(或在严格模式下保持未定义),但在第二种情况下设置为 that。
-
如果
that.replyOK有效,那么您根本不需要that变量。 -
Golergka,是的,确实每个人都有自己的想法。容忍
new的缺失确实是lib' 作者应该考虑的问题(文章的作者John Resig 是jQuery 的创建者)。在您自己的代码中,当调用您自己的 ad hoc 构造函数时,与 lib' 使用者相比,您忘记new的可能性要小得多,但 Resig 的方法肯定会保留在您的工具箱中.
标签: javascript node.js promise q