Reputation: 51
I have created a lambda for dynamodb trigger and it is working ok if I use lambda function with callback but as soon as I change it to async it stops working. It is getting called but call returns before the end of the internal function. I am using await for any async call.
const handler: Handler = async (event: any, context: Context, callback : Callback) => { console.log(event);
try{
// construct request handler
console.log(event.Records);
const createHandler = dummyHandler;
await createHandler.handleRequest(event.Records);
return callback(null, 'Successfully processed ${event.Records.length} records.');
}
catch(err){
console.log(err);
throw err;
}
finally{
console.log('Finally I am here');
}
}
So this code works. Though strangely finally is executed before the handleRequest completes. But still handleRequest does complete as expected.
But since callback is kinda older and unwanted version I am trying to remove it and add promise in my async handler and then it stops working as expected.
const handler: Handler = async (event: any, context: Context): Promise<boolean> =>
{
console.log(event);
try{
// construct request handler
console.log(event.Records);
const createHandler = dummyHandler;
const result = await createHandler.handleRequest(event.Records);
return result;
}
catch(err){
console.log(err);
throw err;
}
finally{
console.log('Finally I am here');
}
}
In my internal function, I am doing few db queries and updates. I am using await in all async calls. But still after my first db query, finally block is being executed. In handler with callback, other db calls still execute but in async version with no callback, after finally is called, nothing else happens and request is ended.
I have checked memory size (256MB) and timeout (300seconds) for lambda function and neither of them are exceeding.
Upvotes: 1
Views: 320
Reputation: 51
So in case anyone else experiences this issue. I ended up making following changes to my async handler without callback.
const handler: Handler = async (event: any, context: Context):Promise<boolean> => {
console.log(event);
try{
// construct request handler
console.log(event.Records);
const createHandler = new ...();
return await createHandler.handleRequest(event.Records);
}
catch(err){
console.log(err);
throw err;
}
finally{
console.log('Event Record');
}
This seems to be working as expected. All my db queries and updates are completed (basically this call createHandler.handleRequest is ended properly) before the request ends. Though needs extensive testing. Still welcome any feedback. Basically it was working with promise but jarmod was right, I just needed to return the await call.
Upvotes: 0