функции игнорируются внутри асинхронной лямбда-функции - PullRequest
2 голосов
/ 14 марта 2019

Я создаю систему, которая проверяет данные игрока, используя API, а затем обновляет мой DynamoDB, но кажется, что он останавливается на полпути?как Let's scan our players & update stats! никогда не показывается в моих журналах?

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!");

            });

        });

    });

};

Я предполагаю, что это как-то связано с моими async & await функциями?может кто-нибудь направить меня в правильном направлении.

1 Ответ

1 голос
/ 14 марта 2019

Вы смешиваете await с then.

Попробуйте:

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!");
    }
};

Способ работы then основан на обратном вызове:

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

Хотя await / async работает, устраняя обратные вызовы и позволяя сделать ваш код синхронным и более читабельным.

const rows = await documentClient.scan(params).promise();
// do something with the rows
...