node.js 如何将 Async 和 Await 与 AWS SDK Javascript 结合使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51328292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:51:53  来源:igfitidea点击:

How to use Async and Await with AWS SDK Javascript

node.jsaws-sdkaws-kms

提问by Kay

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

我正在使用 KMS 库使用 AWS 开发工具包。我想使用 async 和 await 而不是回调。

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?

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

回答by hoangdv

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

如果您使用版本 > 2.x 的 aws-sdk,您可以aws.Request将 a转换为具有链.promise()功能的承诺。对于您的情况:

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

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

keyKMS.Types.GenerateDataKeyResponse-回调的第二个参数(在回调风格)。

The eis a AWSError- The first param of callback func

eAWSError-回调FUNC的第一个参数

note: awaitexpression only allowed within an async function

注意:await表达式只允许在异步函数中使用

回答by zero298

awaitrequires a Promise. generateDataKey()returns a AWS.Request, not a Promise. AWS.Requestare EventEmitters(more or less) but have a promisemethod that you can use.

await需要一个Promise. generateDataKey()返回 a AWS.Request,而不是 a PromiseAWS.RequestEventEmitters(或多或少)但有一种promise您可以使用的方法。

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()
}());