sarp
sarp

Reputation: 3750

How to run async function before AWS Lambda handler triggers

How it would be possible to run an asynchronous function outside of AWS Lambda handler and make use of its output in the handler function? I need to initialize various DB connections asynchronously before the handler function runs. That way the active DB connections can survive upon container reuse.

Example:

var i = 'immediate start';
setTimeout(function(){
  i = 'delayed start';
}, 5000);
module.exports.handler = function (event, context, callback) {
  console.log(i); 
  //outputs `immediate start` whereas I need to have  i = `delayed start` here.
}

Upvotes: 4

Views: 1512

Answers (2)

gaoagong
gaoagong

Reputation: 1255

This may be an answer for a more current lambda version, but you could accomplish this via Top Level Awaits if using Node.js ES modules.

The following article gives some clues of how it could be done and the benefits. Their example is as follows:

// method2 – ES module

// ES module import syntax
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm"; 

const ssmClient = new SSMClient();
const input = { "Name": "/configItem" }
const command = new GetParameterCommand(input);
const parameter = await ssmClient.send(command); // top-level await

export async function handler() {
    const response = {
        statusCode: 200,
        "body": parameter.Parameter.Value
    };
    return response;
};

https://aws.amazon.com/blogs/compute/using-node-js-es-modules-and-top-level-await-in-aws-lambda/

Upvotes: 0

Miguel Coder
Miguel Coder

Reputation: 1949

You would have to create a promise and then resolve the promise whenever your callback function inside of setTimeout() is triggered. Like so:

module.exports.handler = function (event, context, callback) {
    var i = 'immediate start'; 
    return new Promise((resolve, reject) => {
         setTimeout(() => { 
             i = 'delayed start'; 
             resolve()
         })
     })
     .then(()=>console.log(i))
}

Upvotes: 2

Related Questions