Reputation: 718
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?
Upvotes: 3
Views: 5383
Reputation: 191749
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.
Upvotes: 9