16

I am loving using lambda functions in AWS. It ideally reduced my time in maintaining the servers anymore. My question is when using lambda there is context object and the callback function to terminate the function. Is there any use case of using callback over context.

Could anyone tell me the behavior of context.succeed() to callback(error,message)

var startedAt = new Date();

var interval = setInterval(function () {
    console.log(startedAt, new Date());
}, 1000);

exports.handler = function (event, context, callback) {
    setTimeout(function () {
        console.log('returning');
        // v1:
        return callback(null);
        // v2:
        // return context.succeed();
    }, 5000);
};
Chacko
  • 1,506
  • 1
  • 20
  • 42
Naveen Kerati
  • 951
  • 3
  • 13
  • 29

2 Answers2

25

context.succeed is the older way of doing things, and is supported under the 0.10.42 runtime (where the callback parameter specifically isn't). If you're running on the newer runtimes (4.3 and 6.10), it's included for backwards compatibility, but the "proper" way is now to use the callback functionality.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Yes, I agree. But calling a callback() does have the same behavior as context.succeed()? Here https://forums.aws.amazon.com/thread.jspa?messageID=755419 mentioned that there will be unpredictable results if we use the callback(). – Naveen Kerati Dec 20 '17 at 14:07
  • 1
    Use `callback`. – Noel Llevares Dec 20 '17 at 17:51
  • 2
    Can you also clarify what's the role of `return` in all of this? Does it end the event loop instantaneously like `context`, or does it behave someway else? – Mooncrater Jul 09 '21 at 13:41
7

Here callback represented as improvement for context.succeed.

In addition, the event loop allows Node.js to perform non-blocking I/O operations. if callback waits longer then you expect, it means there are other not-completed tasks in the event loop you are not aware of and this is a problem - you should know what tasks are waiting in the queue. You can use the following functions to understand why callback is waiting:

process._getActiveHandles() //gets you handles that are still alive
process._getActiveRequests() //gets you info about active libuv requests.

Freezing the lambda before completing those tasks may lead to unexpected behavior. The next lambda execution can be done on the same container. It means event loop tasks of the previous lambda execution are completed in the current lambda execution.

Also, assuming you have more than one test for exports.handler, with callback every test is independent. With context.succeed, you second test can pass (instead of failing) because of the first test, leaving tasks in the event loop.

elirandav
  • 1,913
  • 19
  • 27