0

I struggle to get my node.js code to function as I want. It is used for an AWS Lambda function.

The code Scan and Output a whole table in a DynamoDB. The issue is I almost never get the console.log("DB SCANNED!") in readdb function outputted in the console ( and no values loaded to "items").

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

var table = "TABLE";

var paramsRead = {
    TableName: table,
  };


exports.handler = async (event) => {

await readdb();
console.log("END");

};


function readdb(){
  ddb.scan(paramsRead, function(err, data) {
    if (err) {
      console.log("Error reading DynamoDB", err);
    } else {
      console.log("DB SCANNED!");
      var items = JSON.stringify(data.Items);
         let response = {
            statusCode: 200,
            body: items,
          };
    }
  }
  );
}

1 Answer 1

3

The Lambda is finishing too quickly because you aren't actually returning anything from readdb to await.

You need to return a Promise

function readdb() {
  return new Promise((resolve, reject) => {
    ddb.scan(paramsRead, (err, data) => {
      if (err) {
        console.log("Error reading DynamoDB", err);
        reject(err);
      } else {
        console.log("DB SCANNED!");
        var items = JSON.stringify(data.Items);
        resolve({
          status code: 200,
          body: items
        });
      }
    })
  });
}

...
const response = await readdb();
Sign up to request clarification or add additional context in comments.

1 Comment

Can't thank you enough for that! It worked like a charm.

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.