I was having problems running some code I wrote using AWS Lambda with NodeJS. It took me some time to narrow my issue down but eventually I noticed that if I call the callback function from a different context than the context of handler function, then the response value is null.
Here's the simple function I used to test that
exports.handler = async (event, context, callback) => {
callback (null,{
statusCode: 201,
headers: {
"Content-Type": "text/html"
},
body: {}
});
}
If I run a test event with this code (test script is an empty JSON) then the result is simply:
Response:
{
"statusCode": 201,
"headers": {
"Content-Type": "text/html"
},
"body": {}
}
However if I only force the callback function to be called in a different context as in the example below:
exports.handler = async (event, context, callback) => {
setTimeout(function() {
callback (null,{ // <-- callback is now called in timer context
statusCode: 201,
headers: {
"Content-Type": "text/html"
},
body: {}
})}, 5000);
}
Then running the exact same test event (empty JSON) now results in a null response:
Response:
null
Now this seems to me like a very basic functionality, I just assume I am missing something here. Can anyone help pinpoint my error? or explain how the response value can contain the required values even if callback is called in a different context?? Thanks!
Update #1 Tested one more time with the use of a promise:




asyncdoesn't do any good.callbackparameter in this case. Did you try to stick to promises and return a value fromasyncinstead of using a callback?