0

Trying to read a dynamoDB table from Alexa Intent , when i execute following block of code getItem() method is being skipped

function alexaIntent(intent, session, callback) {
    var results = "";
    var params = {
        Key: {
            "name": {
                S: "aaa"
            }
        },
        TableName: "bbb"
    };
    console.log('1111111111111111111111111111111');

    /* Code from here till.....*/
    ddb.getItem(params, (err, data) => {
         console.log('inside');
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
       }
    });
    /* .....here is being skipped */

    console.log('2222222');

    callback(session.attributes,
        buildSpeechletResponseWithoutCard("I am the King!!", "", "true"));
}

I am new to asynchronous programming , is there a basic concept / understanding I am missing ?

Output I am getting is :

1111111111111111111111111111111
2222222
Biswadev
  • 1,456
  • 11
  • 24
K.Pil
  • 786
  • 2
  • 10
  • 24
  • If you want logic (like calling the callback you were given to end the function) to wait until you're done with the `getItem` call, then you have to move it to the callback function you're giving to `getItem`. Try moving your `callback(session....` line from the end to inside the function you handed to `getItem` What do you get then? – Jeremy Pridemore Jan 24 '18 at 21:32

1 Answers1

3

Is NOT being skipped. It's just non blocking. The whole point of the second parameter ((err, data) => {...) passed to getItem is to let you know once is done executing. Also, the reason you can't see console.error("Unable to read item... or console.log("GetItem succeeded:" ... is because you are telling the alexaIntent is done before waiting for getItem.

Just move the last callback call to inside the callback provided to getItem:

    ddb.getItem(params, (err, data) => {
             console.log('inside');
            if (err) {
                console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
                callback(session.attributes, buildSpeechletResponseWithoutCard("Error!!", "", "true"));
            } else {
                console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
                callback(session.attributes,
                   buildSpeechletResponseWithoutCard("I am the King!!", "", "true"));
           }
        });
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44