如何使用 AWS SDK Javascript 异步和等待

我正在使用 KMS 库使用 AWS SDK。我想使用异步并等待而不是回调。

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


this.kms = new AWS.KMS();


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

但是,当包装在异步函数中时,这不起作用。

如何使用异步并在这里等待?

34285 次浏览

await requires a Promise. generateDataKey() returns a AWS.Request, not a Promise. AWS.Request are EventEmitters (more or less) but have a Promise0 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()
}());

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

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