81

I am working with the AWS SDK using the KMS libary. I would like to use async and await instead of callbacks.

import AWS, { KMS } from "aws-sdk";

this.kms = new AWS.KMS();

const key = await this.kms.generateDataKey();

However this does not work, when wrapped in an async function.

How can i use async and await here?

1
  • await requires a promise; that takes a callback. Commented Jul 13, 2018 at 15:20

3 Answers 3

130

If you are using aws-sdk with version > 2.x, you can tranform a aws.Request to a promise with chain .promise() function. For your case:

  try {
    let key = await kms.generateDataKey().promise();
  } catch (e) {
    console.log(e);
  }

the key is a KMS.Types.GenerateDataKeyResponse - the second param of callback(in callback style).

The e is a AWSError - The first param of callback func

note: await expression only allowed within an async function

Sign up to request clarification or add additional context in comments.

3 Comments

How can one access key outside of the try statement?
@mbspark you can create key variable at first, outside of the try block. But, why?
I wanted to use key elsewhere in the program. I did end up figuring out what I was trying to do in a different way, though.
18

await requires a Promise. generateDataKey() returns a AWS.Request, not a Promise. AWS.Request are EventEmitters (more or less) but have a promise method that you can use.

import AWS, {
  KMS
} from "aws-sdk";

(async function() {
  const kms = new AWS.KMS();
  const keyReq = kms.generateDataKey()
  const key = await keyReq.promise();

  // Or just:
  // const key = await kms.generateDataKey().promise()
}());

Comments

3

As of 2021 I'd suggest to use AWS SDK for JavaScript v3. It's a rewrite of v2 with some great new features

sample code:

const { KMSClient, GenerateDataKeyCommand } = require('@aws-sdk/client-kms');

const generateDataKey = async () => {
  const client = new KMSClient({ region: 'REGION' });
  const command = new GenerateDataKeyCommand({ KeyId: 'KeyId' });
  const response = await client.send(command);
  return response;
};

AWS SDK for JavaScript v3 new features

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.