1N5*_*818 1 javascript soap asynchronous callback node.js
我真的很难尝试在异步soap请求中调用对象函数。它基本上归结为:
function Thing(request, response) {
this.foo = function() {
console.log("this is foo");
}
this.doThing = function() {
// Get SOAP args
args = { foo: this.request.cookies.foo };
// From the SOAP npm package library
soap.createClient(function(err, client) {
client.doSomething(args, function(err, result) {
// Somehow call foo(); <--- CAN'T FIND A WAY TO DO THIS
});
});
}
}
// Make it so I can access this.request and this.response somehow
Thing.prototype = Object.create(AbstractThing);
Run Code Online (Sandbox Code Playgroud)
我尝试了很多东西,但我相信它从根本上归结为我无法调用this.foo()任何异步肥皂函数的事实。虽然我可以将回调函数传递给createClient,如下所示:
function Thing(request, response) {
this.foo = function() {
console.log("this is foo");
}
this.sendSoap = function(err, client) {
// Get SOAP args
args = {
foo: this.request.cookies.foo <--- this.cookies undefined
};
client.doSomething(args, function(err, result) {
// Somehow call foo(); <--- CAN'T FIND A WAY TO DO THIS
});
}
this.doThing = function() {
// From the SOAP npm package library
soap.createClient(this.sendSoap);
}
}
// Make it so I can access this.request and this.response somehow
Thing.prototype = Object.create(AbstractThing);
Run Code Online (Sandbox Code Playgroud)
我无法再访问 this.request.cookies 因为this现在在sendSoap闭包内部调用。我不知道为什么 javascript 将函数作为对象,但我有点沮丧。
我已经尝试了很多很多事情,但无法找到一种方法来做到这一点并且需要这样做,因为原始调用foo实际上是一个递归函数,我在状态迭代器模式中使用它来在 SOAP Web 服务中进行身份验证我是用Java写的。
我能想到的最后一种方法是修改 SOAP npm 包,以便我可以传递this.cookies到createClient而不仅仅是回调。
我真的没有想法了。任何帮助将不胜感激。
原因是this在回调函数中通常会引用全局窗口范围。
this是 JS 开发人员常见的痛苦来源,而且通常不是指您认为的。您可以在线搜索完整的详细信息。
为什么不这样关闭呢?
function Thing(request, response) {
this.foo = function() {
console.log("this is foo");
}
this.doThing = function() {
var self = this; //Closure to the Thing function
// Get SOAP args
args = { foo: this.request.cookies.foo };
// From the SOAP npm package library
soap.createClient(function(err, client) {
client.doSomething(args, function(err, result) {
self.foo();
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1625 次 |
| 最近记录: |