本文介绍了如何在AWS开发工具包Javascript中使用Async and Await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用KMS库使用AWS开发工具包.我想使用异步和等待而不是回调.

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?

推荐答案

如果使用版本> 2.x的aws-sdk,则可以将aws.Request转换为具有链.promise()函数的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);
  }

keyKMS.Types.GenerateDataKeyResponse-回调的第二个参数(采用回调样式).

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

eAWSError-回调函数的第一个参数

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

注意:await表达式仅在异步函数中允许

note: await expression only allowed within an async function

这篇关于如何在AWS开发工具包Javascript中使用Async and Await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:36
查看更多