简体   繁体   English

在AWS Lambda中使用async关键字

[英]Using async keyword in AWS Lambda

I am playing with AWS Lambda using Node.js. 我正在使用Node.js与AWS Lambda一起玩。 After being tired of having to deal with callbacks I figured I could elegantly use async/await just like I am used to in C#. 在厌倦了必须处理回调后,我想我可以优雅地使用async/await ,就像我在C#中习惯的一样。

exports.handler = async(event, context, callback) => {
    db = await MongoClient.connect(process.env['MONGODB_URI']);
}

Even though this seemingly works when testing offline using lambda-local , it fails miserably when uploaded to AWS. 尽管这在使用lambda-local进行离线测试时似乎有效,但在上传到AWS时却失败了。 It appears as if async keyword is not recognized. 看起来好像无法识别async关键字。 I am using the latest Node.js 6.10 runtime on AWS while my local version is 8.5. 我在AWS上使用最新的Node.js 6.10运行时,而我的本地版本是8.5。 Is there a way around or should I abandon this approach and go back to using callbacks? 有办法还是我应该放弃这种方法并重新使用回调?

The async/await feature was launched in Node.js v7.0 but was behind the --harmony flag as it was experimental. async/await功能是在Node.js v7.0中启动的,但由于它是实验性的,因此位于--harmony标志后面。 It was fully supported without the flag after Node.js v7.6. 在Node.js v7.6之后没有标志完全支持它。

Hence, you can't use async/await with Node.js v6.10. 因此,您不能对Node.js v6.10使用async/await

Look here to know exactly which versions are supported. 在这里查看确切支持哪些版本。

You can bundle your lambda with webpack and babel to write node 8 code and deploy node 6 compatible code. 您可以将lambda与webpack和babel捆绑在一起,编写节点8代码并部署节点6兼容代码。

The easiest way to do this is to use the serverless framework with plugins like : 最简单的方法是使用无服务器框架和插件,如:

Node.js v8.10 runtime is available in AWS Lambda as of April 2nd, 2018. Follow the link below for more information: 自1985年4月2日起,AWS Lambda中提供了Node.js v8.10运行时。请按照以下链接获取更多信息:

https://aws.amazon.com/blogs/compute/node-js-8-10-runtime-now-available-in-aws-lambda/ https://aws.amazon.com/blogs/compute/node-js-8-10-runtime-now-available-in-aws-lambda/

You can also write your handler in Typescript which can compile your code to ES5. 您也可以在Typescript中编写处理程序,它可以将您的代码编译为ES5。

You can use async/await with Typescript. 您可以对Typescript使用async/await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM