2017-11-11 309 views
2

我已經創建了一個基於這個例子Alexa的簡單技能訪問網址:https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.jsAlexa的距離的NodeJS亞馬遜LAMBDA

現在,我想的腳本來登錄一些不同的服務器上,當GetNewFactIntent被稱爲。

這就是我想要做的,但有這個一個問題,這是不應該在http.get回調什麼。

'GetNewFactIntent': function() { 
//var thisisit = this; 
http.get("http://example.com", function(res) { 
    //console.log("Got response: " + res.statusCode); 
    const factArr = data; 
    const factIndex = Math.floor(Math.random() * factArr.length); 
    const randomFact = factArr[factIndex]; 
    const speechOutput = GET_FACT_MESSAGE + randomFact; 

    this.response.cardRenderer(SKILL_NAME, randomFact); 
    this.response.speak(speechOutput); 
    this.emit(':responseReady'); 
}).on('error', function(e) { 
    //console.log("Got error: " + e.message); 
}); 
}, 

在上面這個工作的例子要更換什麼需求?

+0

我不能立即看到問題與該代碼。您能否添加有關其失敗原因的其他信息?需要更多的上下文。 –

回答

1

this不會是你認爲的那樣,因爲你在回調函數的上下文中。有兩個可能的解決方案:

  1. 使用箭頭函數。一個箭頭函數保留了它在其中使用的範圍的this變量: function() { ... } - >() => { }
  2. 聲明var self = this;以外的回調,然後用你的self變量替換你的this回調。

實施例:

function getStuff() { 
    var self = this; 
    http.get (..., function() { 
     // Instead of this, use self here 
    }) 
} 

更多信息,請參見:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

+0

我曾嘗試過_var that = this_之前,但無法讓它工作,但箭頭功能做到了。我不知道它保留了範圍的_this_變量,所以知道這一點很好。非常感謝。 –

+0

很高興看到你能解決你的問題! – NikxDa