【问题标题】:AWS Lambda NodeJS access result of Dynamo DB query from outer function来自外部函数的 Dynamo DB 查询的 AWS Lambda NodeJS 访问结果
【发布时间】:2020-01-20 20:44:09
【问题描述】:

我正在尝试查询 Dynomo DB 表,并且我想在我的 AWS Lambda 中查看函数中的结果项。我无法从 Dynamo DB 查询中提取结果。它在闭包内,我可以控制台记录它,但我无法将它分配给外部函数范围内的任何变量。 我应该怎么做才能把它弄到外面去?

function check(id) {

    //build params
    let params = {
        TableName: 'demo_table',
        KeyConditionExpression: #key =: id,
        Limit: 5,
        ScanIndexForward: false,
        ExpressionAttributeNames: {
            #key: process.env.PRIMARYKEY
        },
        ExpressionAttributeValues: {
            : id: id
        }
    };

    //query ddb
    let result = {};

    ddb.query(params, function(err, data) {
        if (err) {
            console.log("AN ERROR OCCURED\n");
            console.log(err);
        } else {
            //How to copy the data from here to outside??
            //I can console log and see the data
            result = data;
        }

    });
    console.log(result); //returns {}
}


【问题讨论】:

  • 您可以使用异步、回调或承诺来解决此问题。
  • 我在 check() 之外声明了结果。使检查异步。在 ddb.query 之前添加了等待。它仍然返回给我空括号。

标签: javascript aws-lambda amazon-dynamodb


【解决方案1】:
const check = async (id) => {

//build params
let params = {
    TableName: 'demo_table',
    KeyConditionExpression: #key =: id,
    Limit: 5,
    ScanIndexForward: false,
    ExpressionAttributeNames: {
        #
        key: process.env.PRIMARYKEY
    },
    ExpressionAttributeValues: {
        : id: id
    }
};



let result = await new Promise((resolve, rejects) => {
    ddb.query(params, function (err, data) {
        if (err) rejects(err)
        resolve(data)
    });
})


console.log(result); //returns {}
}

通过使用 Promise,您可以获得数据。数据库读取是异步操作。

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2015-12-04
    • 1970-01-01
    • 2021-09-13
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多