简体   繁体   中英

Dynamodb batchWrite doesn't work in Lambda with Async

batchWrite doesn't work with async in Laqmbda. The code is going to insert one record tho, it can't. However, when I remove async, It works.

const AWS = require("aws-sdk");
const documentClient = new AWS.DynamoDB.DocumentClient();

AWS.config.update({ region: "us-west-2" });
const tableName = "BlrSession-56pfbzohnvdqpac6asb627z2wu-dev";
exports.handler = async (event, context, callback) => {
  try {
    let games = [];
    games.push({
      PutRequest: {
        Item: {
          id: Math.random().toString(36).substring(2) + Date.now().toString(36),
        },
      },
    });

    let params = {
      RequestItems: {
        [tableName]: games,
      },
    };

    documentClient.batchWrite(params, function (err, data) {
      if (err) {
        callback(err);
      } else {
        callback(null, data);
      }
    });
  } catch (err) {
    return err;
  }
};

The result is below. There is no error.

Ensuring latest function changes are built...
Starting execution...
Result:
null
Finished execution.

Have you guys got the same behavior?

You can't combine the callback method with the async/await method. The easiest thing to do here is to make it all async/await (and don't forget the .promise() on the call).

const AWS = require("aws-sdk");
const documentClient = new AWS.DynamoDB.DocumentClient();

AWS.config.update({ region: "us-west-2" });
const tableName = "BlrSession-56pfbzohnvdqpac6asb627z2wu-dev";
exports.handler = async (event, context, callback) => {
  try {
    let games = [];
    games.push({
      PutRequest: {
        Item: {
          id: Math.random().toString(36).substring(2) + Date.now().toString(36),
        },
      },
    });

    let params = {
      RequestItems: {
        [tableName]: games,
      },
    };

    return await documentClient.batchWrite(params).promise();
  } catch (err) {
    return err;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM