Reputation: 36311
I am trying to create a master method that handles my json responses, but the issue that I am having is that it hangs when I do.
This is what I had before I converted it, and it worked fine (highscores
returns a Promise
).
var main = {
req: {}, res: {}, action: "",
handleRequest: function(req, res){
this.req = req;
this.res = res;
this.action = "Highscores";
this.getAction();
}),
getAction: function(){
$this = this;
if(this.action === "Highscores"){
highscores.get.highscores({gameId: this.body.gameId}).then(function(docs){
$this.res.setHeader("Content-Type", "text/json; charset=utf-8");
$this.res.setHeader("Access-Control-Allow-Origin", "*");
$this.res.write(JSON.stringify(docs));
$this.res.end();
}, function(err){
$this.res.end();
});
}
}
}
I then converted it to this:
var main = {
req: {}, res: {}, action: "",
handleRequest: function(req, res){
this.req = req;
this.res = res;
this.action = "Highscores";
this.getAction();
}),
getAction: function(){
if(this.action === "Highscores"){
highscores.get.highscores({gameId: this.body.gameId}).then(this.respond, this.error);
}
},
respond: function(docs){
this.res.setHeader("Content-Type", "text/json; charset=utf-8");
this.res.setHeader("Access-Control-Allow-Origin", "*");
this.res.write(JSON.stringify(docs));
this.res.end();
},
error: function(err){
console.log(err);
this.res.end();
}
};
When I convert that, it hangs at this.res.setHeader("Content-Type", "text/json; charset=utf-8");
and the chrome console shows that it is pending, and never finishes with a 200
.
What is causing this?
Upvotes: 0
Views: 103
Reputation: 106696
When you pass functions like that (.then(this.respond, this.error)
), you're losing the context (this
) for that function, because you are merely passing the function itself. So when the respond()
is finally called, the value of this
is probably set to the global context or some other object/value.
A quick and easy way to fix this if you want to keep the same structure is to use bound versions of the functions: .then(this.respond.bind(this), this.error.bind(this))
. Otherwise you'll need to use a wrapper function that calls out to the two functions using the appropriate context (e.g. .then(function(docs) { self.respond(docs) }, function(err) { self.error(err) })
) (assuming you have var self = this
inside getAction()
).
Upvotes: 2