2

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?

1 Answer 1

3

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;
  }
};

Sign up to request clarification or add additional context in comments.

1 Comment

I could do it. I appreciate it, Jason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.