2016-09-20 21 views
0

我正在嘗試構建一個簡單的Alexa技能,使用[Node.js ASK](https://developer.amazon.com/public/community/post/Tx213D2XQIYH864/Announcing-the-Alexa-Skills-Kit-for-Node-js)從API返回數據。我已經把http獲取到一個處理程序中,但是在回調之前Alexa完成處理程序異步返回API數據。Alexa Node.js技能工具包 - 處理程序完成之前需要返回回調數據

我一直在尋找答案,我的想法是現在:

  1. 沒有使用Node.js的
  2. 想出一個辦法來同步獲得數據
  3. 要簡單的我失蹤

核心代碼:

exports.handler = function(event, context, callback) { 
 
    var alexa = Alexa.handler(event, context); 
 
    alexa.registerHandlers(handler); 
 
    alexa.execute(); 
 
}; 
 

 
var handler = Alexa.CreateStateHandler(states.x, { 
 
    'intent': function() { 
 
    var options = { 
 
     host: baseURL, 
 
     path: pathURL 
 
    }; 
 
    
 
    callback = function(response) { 
 
     var str = ""; 
 
     response.on('data', function(piece) { 
 
     str += piece; 
 
     }); 
 
     
 
     response.on('end', function() { 
 
     //does not get executed 
 
     this.emit(':tell', str, "test"); 
 
     }); 
 
    } 
 
    
 
    http.request(options, callback).end(); 
 
    
 
    //this does get executed if I leave this here 
 
    this.emit(':tell'...); 
 
    };

回答

0

我認爲你有一個範圍問題。 嘗試...

response.on('end',() => { 
    this.emit(':tell', str, "test"); 
}); 
相關問題