【问题标题】:how to make AWS dynamo db work in nodejs in using async await如何使用异步等待使 AWS dynamodb 在节点 js 中工作
【发布时间】:2021-12-02 21:07:35
【问题描述】:

我有这个示例发电机数据库创建数据代码

var AWS = require("aws-sdk");
let awsConfig = {
    "region": "ap-south-1",
    "endpoint": "http://dynamodb.ap-south-1.amazonaws.com",
    "accessKeyId": "xxxxxxxxxxxxxxxxx", "secretAccessKey": "xxxxxxxxxxxxxxxxxxxxxxx"
};
AWS.config.update(awsConfig);

let docClient = new AWS.DynamoDB.DocumentClient();

console.log(docClient);

let save = function () {

    var input = {
        "task": "example-1@gmail.com"
    };
    var params = {
        TableName: "todos",
        Item:  input
    };
    docClient.put(params, function (err, data) {

        if (err) {
            console.log("error - " + JSON.stringify(err, null, 2));                      
        } else {
            console.log(data);
        }
    });
}



save();

现在我将其转换为异步等待形式

const create = async (docClient,payload,tableName) =>{
    try {
        console.log(payload);
        const createdDoc = await docClient.put({TableName:tableName,Item:payload})
        console.log(createdDoc);
    } catch (error) {
       console.log(error); 
    }
}
        


create(docClient,{"task":"sample"},"todos")

这段代码既没有给我错误,也没有将数据添加到发电机数据库表中

【问题讨论】:

  • put 是否返回承诺?如果没有,则将整个调用包装在一个 Promise 中,并在完成后在回调中调用 resolve()。

标签: javascript node.js amazon-web-services amazon-dynamodb


【解决方案1】:

您必须根据.put() 调用的结果调用.promise()

const createdDoc = await docClient.put({ … }).promise();

请参阅 AWS.DynamoDB.DocumentClient.put()AWS.Request.promise() 的文档。

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2018-12-30
    • 2020-12-02
    • 2016-12-26
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多