loag
loag

Reputation: 608

Lambda function returns null from nested async function

The Lambda function is not hitting the memory limit neither timing out. I read somewhere that it may return because the event loop is empty but I have context.callbackWaitsForEmptyEventLoop set to false.

Here is the function:

module.exports.callMenu = (event, context, callback) => {

  context.callbackWaitsForEmptyEventLoop = false;
  const eventJSON = qs.parse(event.body);
  myMongooseObject.findOne({ value: eventJSON.value }, (err, theObject) => {
    if (!err) {

      newObj = new myMongooseObject();
      newObj.message = 'this worked';

      newObj.save((err) => {
        if (!err) {
          callback(null, { body: 'success' });
        } else {
          console.log(err);
        }
      });
    }
};

Upvotes: 0

Views: 1883

Answers (1)

Zanon
Zanon

Reputation: 30760

In your code, you are not adding callbacks for when there is an error in the request. And you may want to add a try/catch to handle any other issues with your code.

Also, you don't need to set callbackWaitsForEmptyEventLoop because you are not adding extra events besides your main request.

Try this:

const myMongooseObject = defineThisObject(); // maybe you forgot to define it
const qs = defineThisObjectToo(); // maybe another error

module.exports.callMenu = (event, context, callback) => {

    try {
        const eventJSON = qs.parse(event.body);
        myMongooseObject.findOne({ value: eventJSON.value }, (err, theObject) => {

            if (!err) {
                newObj = new myMongooseObject();
                newObj.message = 'this worked';

                // define the newCall object too?

                newCall.save((err) => {
                    if (!err) {
                        callback(null, { body: 'success' });
                    } else {
                        callback(err); // add this
                    }
                });
            } else {
                callback(err); // add this
            }
        });
    } catch (e) {
      callback(e);
    }
};

Upvotes: 2

Related Questions