1

我是 aws lambda 的新手,我无法找到为什么在这个简单的代码中使用 dynamoDB 时没有得到任何响应或错误:

var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.KrakatoaProcessEventHandler = function(event, context) {
        //console.log(JSON.stringify(event, null, 2));

    dynamodb.listTables(function(err, data) {
     console.log(err);
     console.log(JSON.stringify(data, null, '  '));
    });

    event.Records.forEach(function(record) {
        // Kinesis data is base64 encoded so decode here
        payload = new Buffer(record.kinesis.data, 'base64').toString('ascii');
        console.log('Decoded payload:', payload);
    });
    context.succeed("Foo");

};

总体反应是:

START RequestId: 6f7b57f6-f3fc-11e4-9beb-f5a3878e8dc1
2015-05-06T14:30:28.653Z    6f7b57f6-f3fc-11e4-9beb-f5a3878e8dc1    Decoded payload: Hello, this is a test 123.
2015-05-06T14:30:28.711Z    6f7b57f6-f3fc-11e4-9beb-f5a3878e8dc1    result: "Foo"
END RequestId: 6f7b57f6-f3fc-11e4-9beb-f5a3878e8dc1
REPORT RequestId: 6f7b57f6-f3fc-11e4-9beb-f5a3878e8dc1  Duration: 478.16 ms Billed Duration: 500 ms     Memory Size: 128 MB Max Memory Used: 13 MB  

我尝试使用具有相同行为的 dynamodb.putItem,一切似乎都是正确的,但我没有得到任何响应或错误。

提前致谢。

4

1 回答 1

3

您传递给的匿名函数dynamodb.listTables()是一个回调。像这样想他们:

dynamodb.listTables(function(err, data) {
    // Done listing tables, now do stuff!
});

// If you put code here, it's not guaranteed to run *after* listTables()

只要您调用 Lambda 函数就会停止执行context.succeed()。因此,由于您将此称为 的“外部” listTables(),因此 Lambda 函数可能会在您从 Dynamo 获得任何结果之前停止。

正如您在评论中指出的那样,解决方案是执行以下操作:

dynamodb.listTables(function(err, data) {
    // Done listing tables, now do stuff!

    context.succeed('Foo');
});

因为你把context.succeed()回调放在里面,这保证了这个函数只有Dynamo 返回一个结果并且你用它做事情之后才完成。

异步编程有点棘手,直到你掌握它的窍门,所以阅读回调,你可以在将来避免这个错误!

于 2015-05-06T18:28:22.610 回答