admin管理员组

文章数量:1295947

I'm creating an AWS SAM application using Node.js Lambda functions. The default template has an async handler function:

exports.lambdaHandler = async (event, context) => {
  // ...
  return {
    statusCode: 200,
    body: JSON.stringify({ hello: "world" })
  };
};

Is there any benefit to having this handler function be async vs sync, since my understanding is each time a Lambda function is invoked it runs separately from other instances?

I'm creating an AWS SAM application using Node.js Lambda functions. The default template has an async handler function:

exports.lambdaHandler = async (event, context) => {
  // ...
  return {
    statusCode: 200,
    body: JSON.stringify({ hello: "world" })
  };
};

Is there any benefit to having this handler function be async vs sync, since my understanding is each time a Lambda function is invoked it runs separately from other instances?

Share asked May 10, 2021 at 16:25 A PoorA Poor 1,0641 gold badge14 silver badges32 bronze badges 1
  • 3 async allows you to use await in the function body. If you're not using await, then there is very little reason to use async. – VLAZ Commented May 10, 2021 at 16:26
Add a ment  | 

2 Answers 2

Reset to default 7

AWS Lambda handles synchronous functions and asynchronous functions as well. async means two things:

  • The function returns a Promise
  • You are able to use await inside it

AWS Lambda happens to understand Promises as return value, thats why async functions work as well. So if you need await just go for async.

You could also not declare the function as async and return a Promise (or chain of Promises)

use async handler function if you want to use return and throw to send a response or error respectively from your function handler.

you can use non-async handler but it only terminates the function execution when the event loop is empty or the function times out.

ref: https://docs.aws.amazon./lambda/latest/dg/nodejs-handler.html

本文标签: