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
How to use Async and Await with AWS SDK Javascript
提问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).
的key是KMS.Types.GenerateDataKeyResponse-回调的第二个参数(在回调风格)。
The eis a AWSError- The first param of callback func
该e是AWSError-回调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 Promise。 AWS.Request是EventEmitters(或多或少)但有一种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()
}());

