Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run synchronous dynamodb request in lambda?

const params = {
  TableName: 'item-table',   
  FilterExpression : "#tagname = :itemId",
  ExpressionAttributeNames: {"#tagname": "itemId"},
  ExpressionAttributeValues: {":itemId": "000001"}    
    };
var item ="";
dynamo.scan(params, function(err, data)
{
 if (err) {
    console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
    item = err;
    } else {
        console.log("Query succeeded.");
        data.Items.forEach(function(item) {
          item += item.itemName;
      });
      }
      return item;
});

Scan is not waiting to return the output but going to next step. How can we run synchronous call from lambda to dynamodb.

like image 518
Vikash Avatar asked Nov 06 '17 15:11

Vikash


1 Answers

If you really need synchronous scan, you can use one of the ways below:

1. Using Promise resource of JavaScript:

const params = {
    TableName: 'item-table',   
    FilterExpression : "#tagname = :itemId",
    ExpressionAttributeNames: {"#tagname": "itemId"},
    ExpressionAttributeValues: {":itemId": "000001"} };

function scan(params) {
  return new Promise((resolve, reject) => {
    dynamo.scan(params, (err, data) => {
      if (err)
        reject(err);
      else
        resolve(data);
    };
  };
}

async function syncScan() {
  var data;
  try {
    data = await scan(params);
    console.log("Query succeeded.");
  }
  catch (err) {
  console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
  }
        
  return data;
}

syncScan();

2. Using the aws-sdk return objects:

const AWS = require('aws-sdk');
AWS.config.update({ region: 'sa-east-1' });
const docClient = new AWS.DynamoDB.DocumentClient();

async function syncScan() {

  const params = {
    TableName: 'item-table',   
    FilterExpression : "#tagname = :itemId",
    ExpressionAttributeNames: {"#tagname": "itemId"},
    ExpressionAttributeValues: {":itemId": "000001"} 
  };

  const awsRequest = await docClient.scan(params);
  const result = await awsRequest.promise();
  console.log(result.Items); // <<--- Your results are here
}

syncScan();
like image 87
Felipe Jacob Avatar answered Oct 26 '22 17:10

Felipe Jacob