【发布时间】:2018-05-05 23:36:30
【问题描述】:
我是 Skill 和 nodejs 开发的新手,很快就遇到了我的第一个问题。
基本上,我正在尝试从 DynamoDB 读取数据并让它通过 Alexa 说话。
var title;
exports.handler = (event, context, callback) => {
getData();
alexa = Alexa.handler(event, context, callback);
alexa.appId = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
const handlers = {
'LaunchRequest': function () {
this.emit('DoSomethingIntent');
},
'DoSomethingIntent': function () {
this.response.speak('Here are your data ' + title);
this.emit(':responseReady');
},
};
function getData() {
var ddb = new AWS.DynamoDB.DocumentClient({region:'eu-west-1'});
var params = {
TableName: 'data',
Key: {'data_id' : 1,},
};
ddb.get(params, function(err, data) {
if (err) {
}else{
title = data.Item.title;
}
});
}
问题在于 DynamoDB.DocumentClient.get 函数异步运行,同时 DoSomethingIntent 运行时标题变量未定义。
解决此问题的最佳做法是什么?
到目前为止,唯一对我有用的解决方案是:
ddb.get(params, function(err, data) {
if (err) {
}else{
title = data.Item.title;
alexa.registerHandlers(handlers);
alexa.execute();
}
});
但对我来说似乎不太实用!
【问题讨论】:
-
在
DoSomethingIntentIntent 中调用get方法。 -
那不行。 ddb.get(params, function(err, data) { });异步运行。
-
'DoSomethingIntent': function () { getData(callback(title) { this.response.speak('Here are your data ' + title); this.emit(':responseReady'); } ) }
-
谢谢@PriyamGupta 就是这样!
标签: javascript node.js amazon-dynamodb aws-lambda alexa