0
votes

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?Mark B

1 Answers

4
votes

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.