我正在嘗試創建一個處理我的json響應的主方法,但是我遇到的問題是它在我執行時掛起。節點響應掛起
這是我在轉換它之前所做的,它工作正常(highscores
返回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();
});
}
}
}
我然後轉換成這樣:
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();
}
};
當我轉換的是,它掛在this.res.setHeader("Content-Type", "text/json; charset=utf-8");
和鉻控制檯顯示它正在等待,從不與200
完成。
這是什麼造成的?
我不熟悉promise,但我不認爲''this''指針在你的'respond'方法中是你認爲的。例如:http://jsfiddle.net/jomk9axz/這個小提琴顯示'this'指針指向'window'對象而不是'a'對象。 –