'Handling consecutive DynamoDB calls in a node.js Lambda for AWS

My example is quite simple. I am using AWS Lambda in proxy mode where the index.js looks like this.

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

I have a separate app.js file which has a POST endpoint. Inside this endpoint I need to make two queries on a DynamoDB table.

I need to first query the table to determine if something exists. My code looks like this.

// DynamoDB Document Client
const docClient = new AWS.DynamoDB.DocumentClient();
app.post('/profile/:userSub', (req, res) => {
  const userSub = req.params.userSub;
  const accountName = req.body.accountName; 

  // First query
  const params = {
    TableName: profileTableName,
    IndexName: profileIndexAccountName,
    KeyConditionExpression: 'accountName = :accountName',
    ExpressionAttributeValues: {
      ':accountName' : accountName
    }
  };

  docClient.query(params, (err, data) => {
    // Process the results
     
  });
}

The problem is that I want to do a follow up query docClient.put based on the results from the first query.

I don't understand how to chain the queries together so that the first one is completed before the second one is executed.

Can someone please point me to an example? Or alternatively, if there's a better using async/await then I'm happy to follow it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source