0

How do you use async version of dynamo functions such as getItem()?

My code example:

import aws from 'aws-sdk';
import { AppError } from 'errors/AppError';
import { Request, Response } from 'express';
import { injectable } from 'tsyringe';
import { promisify } from 'util';

@injectable()
export class CreateMonitorActivityController {
  async handle(req: Request, res: Response): Promise<Response> {
    aws.config.update({region: 'us-east-1'});
    const DDB = new aws.DynamoDB({
      apiVersion: '2012-08-10',
    });

    const params = {
      TableName: String(table_name),
      Key: {
        'base_activity_id': {
          S: String(base_activity_id)
        }
      }
    };

    const result = DDB.getItem(
      params,
    );

    console.log(result);

    return res.send(result);
  }
}

In this case I just want to return the result, but the code doesn't wait the getItem() method to end.

I already tried to use the promisify from NodeJS utils and the bluebird but didn't fix.

2
  • const result = await DDB.getItem(... ? Commented May 17, 2022 at 19:10
  • Thanks, it didn't solve but made me find the solution as I said in the answer! Commented May 17, 2022 at 19:30

1 Answer 1

1

Figured out, when using the await before the DDB.getItem() it was not working, but adding a promise() in the end made it works.

Fixed code:

import aws from 'aws-sdk';
import { AppError } from 'errors/AppError';
import { Request, Response } from 'express';
import { injectable } from 'tsyringe';

@injectable()
export class CreateMonitorActivityController {
  async handle(req: Request, res: Response): Promise<Response> {
    const {
      table_name,
      base_activity_id,
    } = req.query;

    aws.config.update({region: 'us-east-1'});
    const DDB = new aws.DynamoDB({
      apiVersion: '2012-08-10',
    });

    const params = {
      TableName: String(table_name),
      Key: {
        'base_activity_id': {
          S: String(base_activity_id)
        }
      }
    };

    const result = await DDB.getItem(
      params,
    ).promise();

    return res.send(result)
  }
}
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.