How to use Async and Await with AWS SDK Javascript

非 Y 不嫁゛ 提交于 2019-11-30 07:52:24

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

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()
}());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!