简体   繁体   中英

Simple AWS Lambda response is null if callback is called in different context

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!

同步代码与工作结果 响应为空的异步代码 测试事件-空的JSON对象

Update #1 Tested one more time with the use of a promise:

另一个有希望的测试

Your code will return immediately before the callbacks are invoked. That's why it works in the first example.

Try adding await to the front of your Promise example so that node completes the work before moving on.

const value = await delay(5000)
callback(null, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM