Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from DynamoDB with Lambda nodejs for Alexa Skill

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!

like image 469
Joe Fred Avatar asked Sep 18 '26 22:09

Joe Fred


1 Answers

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.

like image 71
Vijayanath Viswanathan Avatar answered Sep 21 '26 11:09

Vijayanath Viswanathan