0

The following code works fine in nodejs 6.1

console.log('Starting function registration');

const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-central-1'});
const docClient = new AWS.DynamoDB({apiVersion: '2012-10-08'});

exports.handler = function(event, context, callback) {

    var params = {
      'TableName' : 'services',
      'Item': {
         'name': {S: 'test'},
         'phone': {S: '0742324232'},
         'available': {BOOL: true}
         }
    };  

    docClient.putItem(params, function(err, data) {
      if (err) {
        console.log("Error", err);
        callback(err);
      } else {
        console.log("Success", data);
        callback(data);
     }});
};

Yet, when trying to use it in nodejs 8.1 style, It doesn't write anything to the database:

console.log('Starting function registration');

const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-central-1'});
const docClient = new AWS.DynamoDB({apiVersion: '2012-10-08'});

exports.handler = async (event, context, callback) => {

    var params = {
      'TableName' : 'services',
      'Item': {
         'name': {S: 'test2'},
         'phone': {S: '0742324232'},
         'available': {BOOL: false}
         }
    };  

    var {err, data} = await docClient.putItem(params);
    return data;
};

I feel like I'm missing something about the usage of async/await but can't figure out what. What's the proper way to write an item to DynamoDB using nodejs 8.1 and lambda functions?

1
  • Have you tried checking the value of err to see what the issue is? Commented Jul 14, 2018 at 13:14

1 Answer 1

4

It would not work with plaintiff async/ await because putItem ( or, in general, any of the dynamdb methods if you us them via the aws-sdk ) is a callback method where it returns the data and the error. Async / await works with promises and not callbacks.

You may wish to promisify the dynamodb methods to make them work with async / await.

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

Comments

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.