Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execution not waiting for promise result in AWS Lambda

I'm trying to use promises in AWS Lambda and am having some trouble. I'm using typescript/nodejs; see code below

export function handler(event: any, context: any, callback: Function){

    testFunction().then(data => callback(null, "success from promise"));
    callback(null, "success");
}   

export function testFunction(){
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve("data"), 5000);
    });
}

When I run the code I'm getting the "success callback" instead of the "success from promise". Am I doing something wrong here?

like image 975
mattc19 Avatar asked Feb 27 '26 22:02

mattc19


1 Answers

You are actually calling the callback twice: once on the fourth line "success" and once after the promise resolves. I think that lambda will essentially ignore the second callback (which is actually first in your code).

You can merely remove the other call:

export function handler(event: any, context: any, callback: Function){
    testFunction().then(data => callback(null, "success from promise"));
}

Note: the callback is only supported by Node 4.3. It is also optional. You only need to use it if you want to explicitly pass data back to the caller. Otherwise it will be called automatically once the event loop is empty which in this case will happen after the promise resolves.

You can also change the setting of context.callbackWaitsForEmptyEventLoop = false if you want the lambda function to end immediately when callback is called instead of waiting for the event loop to finish. Most likely you won't need to do this, though.

like image 150
Explosion Pills Avatar answered Mar 02 '26 15:03

Explosion Pills