Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Async and Await with AWS SDK Javascript

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?

like image 633
Kay Avatar asked Jul 13 '18 15:07

Kay


People also ask

Can I use async await in JavaScript?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.

Is AWS SDK async?

Advanced operations. The AWS SDK for Java 2. x uses Netty , an asynchronous event-driven network application framework, to handle I/O threads.

How is async await implemented in JavaScript?

JavaScript Async FunctionsAsync and await are built on promises. The keyword “async” accompanies the function, indicating that it returns a promise. Within this function, the await keyword is applied to the promise being returned. The await keyword ensures that the function waits for the promise to resolve.


Video Answer


2 Answers

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

like image 96
hoangdv Avatar answered Oct 13 '22 01:10

hoangdv


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() }()); 
like image 20
zero298 Avatar answered Oct 13 '22 01:10

zero298