Async/await on AWS lambda function for NodeJS

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 a syntactic sugar on top of promises.

Example

// This will work on Node 8.10 environment
function squareOfNumberAfter2Seconds(number) {
return new Promise((resolve) => {
setTimeOut(() => {
resolve(number * number)
}, 2000)
})
}
async function calculate() {
try {
let responseOne = await squareOfNumberAfter2Seconds(10);
let responseTwo = await squareOfNumberAfter2Seconds(20);
let responseThree = await squareOfNumberAfter2Seconds(40);
return responseOne + responseTwo + responseThree;
}
catch(error) {
return error;
}
}
// Noticeable change in function parameters, there is no callback
exports.handler = async (event) => {
let calculationResult = await calculate();
return calculationResult;
}

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 .