【发布时间】:2017-11-20 18:45:15
【问题描述】:
我正在尝试从 aws lambda 函数调用 REST 服务,但执行并未触发回调函数内的代码。 REST 服务在独立的 node.js 服务器上运行良好。
在 CourseInfoIntent 中,我正在获取槽值并形成一个端点 url。我已经创建了带有所需值的 https_options_get。
exports.handler = function(event, context, callback){
console.log("Course Info Skill Started");
var alexa = Alexa.handler(event, context);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
const handlers = {
'LaunchRequest': function(){
console.log("Inside Launch Request");
this.emit('CourseInfoIntent');
},
'CourseInfoIntent': function(){
// fetch the lesson id from data as per slot_type(Lesson) value
console.log("Course Info Intent Started");
//this.event.request.intent.slots.slotname.value for retrieving slot value from utterance
var req_lesson = this.event.request.intent.slots.Lesson.value;
console.log("Lesson Requested: " + req_lesson);
var lessonId = data[req_lesson];
console.log("Lesson ID: " + lessonId);
path = path + '?LessonID='+lessonId;
var url = "https://" + hostName + path;
console.log("Rest url is :-> " + url);
// create opyions for https request
var https_options_get = {
host: hostName,
method: 'GET',
path: path,
headers: {
'Content-Type': 'application/json'
}
};
var result = getJson(https_options_get, function(err){
console.log("Inside callback function");
const speechOutput = "There has been an error with your request" + err;
this.response.speak(speechOutput);
this.emit(':responseReady');
});
const speechOutput = "The name of the lesson is " + result;
const reprompt = "Do you like to know about more sessions? Answer Yes or No";
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');
}
getJson 函数用于使用 node.js https 模块进行 REST 调用。但是在 cloudwatch 中检查日志时,我只能看到日志,直到函数调用 var request = https.request(https_options_get, function (response) {} 后的“Inside new getJson function:”日志消息没有触发。
function getJson(https_options_get, context, callback) {
console.log("Inside new getJson function: ");
var request = https.request(https_options_get, function (response) {
console.log('In GET Request Function block');
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
var bodyJSON = JSON.parse(body);
console.log('bodyJSON:-> ' + bodyJSON );
var result = bodyJSON.LessonName;
console.log('result:-> ' + result );
return result;
});
response.on('error', callback);
})
.on('error', callback)
.end();
// end() should be placed above so that the control know we are done with the request and it can now send it to server
}
谁能告诉我这里做错了什么。
【问题讨论】:
-
你不应该返回
result你应该将它传递给回调。现在你只在出现错误时调用callback函数。您还需要在调用成功时调用callback。我不建议尝试同时学习 NodeJS 和 AWS Lambda。同时 Python 更容易学习,因为您不必处理异步回调。 -
嗨,马克,你能不能让我明白返回结果(期望它在父函数中处理)而不是使用回调函数处理结果有什么区别。
-
当你异步调用一个函数时,调用者不能等待返回值。这就是使用回调函数的原因。您缺少对异步函数调用如何工作的基本理解。这就是为什么我建议用 Python 编写函数的原因,因为您不必处理异步调用并且返回值将按您的预期工作。
标签: node.js amazon-web-services aws-lambda alexa alexa-skills-kit