Iam new to Skill and nodejs development and got my first problem very soon.
Basically, iam trying to read data from DynamoDB and let it speak over 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;
}
});
}
The problem is that the DynamoDB.DocumentClient.get function is running asynchron and at the same time when the DoSomethingIntent runs the title variable is undefined.
What would be the best practice to solve this problem?
The only Solution which has worked for me so far was that:
ddb.get(params, function(err, data) {
if (err) {
}else{
title = data.Item.title;
alexa.registerHandlers(handlers);
alexa.execute();
}
});
But it does not seem very practical for me!
Your working solution is correct because if you write the execution logic then it will run before it completes Dynamodb callback. Please remember DynamoDB call is Asynchronous non-blocking I/O so it will not block any code to execute outside the callback. So better place to add Alexa execution logic is inside callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With