2015-05-11 71 views
0

我正在嘗試創建一個處理我的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完成。

這是什麼造成的?

+2

我不熟悉promise,但我不認爲''this''指針在你的'respond'方法中是你認爲的。例如:http://jsfiddle.net/jomk9axz/這個小提琴顯示'this'指針指向'window'對象而不是'a'對象。 –

回答

2

當你傳遞那樣的函數(.then(this.respond, this.error))時,你就失去了該函數的上下文(this),因爲你只是傳遞函數本身。所以當最後調用respond()時,this的值可能被設置爲全局上下文或其他對象/值。

如果你想保持相同的結構,一種快速簡單的方法來解決這個問題,就是使用函數的綁定版本:.then(this.respond.bind(this), this.error.bind(this))。否則,您需要使用包裝函數,該函數使用適當的上下文調用兩個函數(例如.then(function(docs) { self.respond(docs) }, function(err) { self.error(err) }))(假設您在getAction()內部有var self = this)。

+0

看起來是這個問題,使用綁定工作!謝謝 –