Javier Navarro
Javier Navarro

Reputation: 25

Async code to retrieve documents from dynamodb is never executed

The code that should be executed when the DynamoDB finishes is never executed.

Even though I am using scan's built-in promise, the await is not waiting for the scan to finish. Even manually adding an additional await command, it does not get it executed.

    var AWS = require("aws-sdk");
    AWS.config.update({
          region: "us-west-2",
          endpoint: "http://localhost:8000"
        });
    var docClient = new AWS.DynamoDB.DocumentClient(); 
        var params = {
                TableName : "residenciaLN",            
            };


    exports.handler = async (event) => {
        console.log("Querying...");

        const load = async () => {
            console.log("Got in...");
            const { Items } = await docClient.scan(params).promise();
            const item = Items[0];
            console.log('Items: ' + item);
            return;
        };
        await load;   // no effect on this line being here or not
        console.log("Exiting...");   
        return 
    }; 

    Actual result:
    INFO    Querying...
    INFO    Exiting...

    Expected result: 
    INFO    Querying...
    INFO    Got in...
    INFO    Items: XXXXXX
    INFO    Exiting...

Upvotes: 0

Views: 159

Answers (2)

Sarthak
Sarthak

Reputation: 183

you need to call load as a function await load() instead of await load

exports.handler = async (event) => {
    console.log("Querying...");

    const load = async () => {
        console.log("Got in...");
        const { Items } = await docClient.scan(params).promise();
        const item = Items[0];
        console.log('Items: ' + item);
        return;
    };
    await load();   // instead of [await load]
    console.log("Exiting...");   
    return 
}; 

Upvotes: 0

Murat
Murat

Reputation: 1205

load is a function. To trigger a function call you have to use parenthesis after it.

To make it work, change this line:

await load;

To this :

await load();

Upvotes: 1

Related Questions