Lambda函数从嵌套的异步函数

时间:2017-07-05 21:34:15

标签: node.js amazon-web-services asynchronous aws-lambda serverless-framework

Lambda函数没有达到内存限制,也没有超时。我在某处读到它可能会返回,因为事件循环为空但我将context.callbackWaitsForEmptyEventLoop设置为false

这是功能:

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);
        }
      });
    }
};

1 个答案:

答案 0 :(得分:1)

在您的代码中,您不会在请求中出现错误时添加回调。您可能需要添加try / catch来处理代码中的任何其他问题。

此外,您无需设置callbackWaitsForEmptyEventLoop,因为除主要请求外,您不会添加额外的活动。

试试这个:

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);
    }
};
相关问题