I am experiencing an issue with AWS Lambda with Node 8.10 existing early with the implicit null returned callback:
const request = require('request');
exports.handler = async (event, ctx, callback) => {
console.log(`Fetching '${event.url}'...`);
request(event.url, (err, body) => {
if (err) return callback(err);
return callback(null, body);
});
}
This is a basic example of the problem I have in my own much larger lambda function. Essentially, when I make a call to a 3rd party resource, the Lambda finishes before the callback is reached.
I have read several documentation pages and SO posts that refer to:
callbackWaitsForEmptyEventLoop but setting this to false does not change the behaviour.
I have managed to force it to wait for the response by wrapping the code in a promise then using await before calling callback but is this really necessary?
exports.handler = async (event, ctx, callback) => {
const executeLambda = new Promise((resolve, reject) => {
console.log(`Fetching '${event.url}'...`);
request(event.url, (err, body) => {
if (err) return reject(err);
return resolve(body);
});
});
await executeLambda
.then((res) => callback(null, res))
.catch(callback);
}
Note: I am mocking this locally with docker run --rm -v "$PWD":/var/task lambci/lambda:nodejs8.10 index.handler '{"url": "https://www.google.com"}'