异步lambda函数中忽略的函数

时间:2019-03-14 10:53:10

标签: node.js asynchronous lambda amazon-dynamodb async.js

我正在创建一个系统,该系统使用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!");

            });

        });

    });

};

我假设这与我的asyncawait函数有关?有人可以指出我正确的方向。

1 个答案:

答案 0 :(得分:1)

您正在将awaitthen混合。

尝试一下:

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
相关问题