nodejs lambda async handle don't finished after await function

Viewed 45

I am creating a simple lambda function that connects with documentdb.

serverless.yml

# ...
functions:
  helloWorld:
    handler: src/handlers/helloWorld.handler
    events:
      - httpApi:
          path: /
          method: get

src\handlers\helloWorld.js

"use strict";

const { mongoClient } = require("../helpers/dbHelper");

module.exports.handler = async (event, context) => {
  try {
    const db = await mongoClient();
    const data = await db.collection("mytable").find({}).toArray();

    console.log(data);

    return {
      statusCode: 200,
      body: JSON.stringify({ message: "hello world" }),
    };
  } catch (error) {
    console.log(error.message);
    throw error;
  }
};

The data variable is correctly queried and the return function works as expected, but the function just doesn't finish, until timeout.

If I put the hardcoded return above the mongoClient(), the function will finish as normal.

1 Answers

Turns out it missed the vpc config

provider:
  # ...
  vpc:
    securityGroupIds:
      - sg-xxxxxxxxxxxxx
    subnetIds:
      - subnet-xxxxxxxxxxx
      - subnet-xxxxxxxxxx
      - subnet-xxxxxxxxxxxxx
Related