Async/await on AWS Lambda function for NodeJS

Parag Poddar
Tensult Blogs
Published in
1 min readApr 13, 2018

This Blog has moved from Medium to blogs.tensult.com. All the latest content will be available there. Subscribe to our newsletter to stay updated.

Lambda is a compute service in AWS. By lambda we can run serverless applications. For further details go to this link.

Async/await

Using async/await we can write asynchronous function and simplify promise chain. Await keyword is valid only in an async function. ECMAScript 2017 brought this feature which is syntactic sugar on top of promises.

Example

In handler() we are calling calculate() which is asynchronous and it returns a resolved promise after the calculation.

In calculate()we are calling squareOfNumberAfter2Seconds() three times with a parameter, one after another asynchronously and once we receive a response from one function call, it will proceed to the next one. Here we have used a normal try-catch for handling errors. This is an important step required, otherwise it will show anunhandled promise rejections warning.

In squareOfNumberAfter2Seconds() we are calculating square of a number and sending as a resolved promise after 2 seconds.

This is a better way to write more readable asynchronous code than using the promise chain. Also it almost behaves like a synchronous code .

--

--