2

I'm creating a system that checks player data using an API and then updates to my DynamoDB but appears it stops half way through? as the Let's scan our players & update stats! is never shown inside my logs?

exports.handler = async (event, context) => {

    var documentClient = new AWS.DynamoDB.DocumentClient();

    var params = {
        TableName: 'games',
        FilterExpression:'updated_at = :updated_at',
        ExpressionAttributeValues: {
            ":updated_at": 0,
        }
    };
    var rows = await documentClient.scan(params).promise();

    let gameAPI = new GameAPI();

    await gameAPI.login().then(function() {

        console.log("We have logged into our game!");

        rows.Items.forEach(function(match) {

            console.log("Let's look at our match! " + match.id);

            var player_params = {
                TableName: 'players',
                FilterExpression:'match_id = :match_id',
                ExpressionAttributeValues: {
                    ":match_id": match.id,
                }
            };

            documentClient.scan(player_params).promise().then(row => {

                console.log("Let's scan our players & update stats!");

            });

        });

    });

};

I'm assuming it's something to do with my async & await functions? could someone point me in the right direction.

Zobia Kanwal
  • 4,085
  • 4
  • 15
  • 38
Curtis
  • 2,646
  • 6
  • 29
  • 53

1 Answers1

1

You are mixing await with then.

Try this:

exports.handler = async (event, context) => {

    var documentClient = new AWS.DynamoDB.DocumentClient();

    var params = {
        TableName: 'games',
        FilterExpression:'updated_at = :updated_at',
        ExpressionAttributeValues: {
            ":updated_at": 0,
        }
    };
    var rows = await documentClient.scan(params).promise();

    let gameAPI = new GameAPI();

    await gameAPI.login();

    console.log("We have logged into our game!");

    for (let match of rows.Items) {

        console.log("Let's look at our match! " + match.id);

        var player_params = {
            TableName: 'players',
            FilterExpression:'match_id = :match_id',
            ExpressionAttributeValues: {
                ":match_id": match.id,
            }
        };

        let row = await documentClient.scan(player_params).promise();
        console.log("Let's scan our players & update stats!");
    }
};

The way then works is callback based:

documentClient.scan(params).promise().then((rows) => {
    // do something with the rows
});

While await / async works by eliminating the callbacks and enabling you to make your code look synchronous and more readable.

const rows = await documentClient.scan(params).promise();
// do something with the rows
Romeo
  • 521
  • 5
  • 20