1

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"}'

1 Answer 1

2

The problem was that I declared the handler with async. The following works:

const request = require('request');

exports.handler = (event, ctx, callback) => {
    console.log(`Fetching '${event.url}'...`);
    request(event.url, (err, body) => {
        if (err) return callback(err);
        return callback(null, body);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.