How can I list all my Amazon EC2 instances using Node.js in AWS Lambda?

As of 2019 (October), the given answer didn't help, after digging I found now it is promise based

exports.handler = async function(event) {
  const promise = new Promise(function(resolve, reject) {
      //your logic, goes here at the end just call resolve 
      resolve("data you want to return"); // here lamda exits 
    })
  return promise;// lamda does not  exits here, it waits for to resolve
}

The most likely cause is that you are explicitly terminating your Lambda function before it completes the call to EC2 DescribeInstances API.

The reason is that Lambda assumes your code has finished executing as soon as you call context.done(...). And this is happening before the console.log(... data ...) call.

This weird ordering happens because of how NodeJS works and how the AWS SDK for JavaScript works. In NodeJS you should never block the execution. A call to a webservice (such as EC2) would block the execution. Therefore the AWS SDK for JavaScript (as well as most NodeJS libraries) works by making an asynchronous call.

Most often, when you have an asynchronous call, you pass a callback function to that call. When the results are ready, NodeJS will execute the callback function.

In your code, that function(err, data) {...} is the callback function. This is not executed immediately, but will be scheduled for execution when NodeJS sees that the ec2.describeInstances call has received the its results.

As soon as you schedule the execution of your call back, you are calling context.done(...), which tells Lambda: I'm done, you can kill me. And it's happily obeying and interrupting your function, before the EC2 DescribeInstances call receives its data and passes it to your callback function.

How to solve the problem?

The answer should be clear by now: just move your context.done(...) call to inside your callback function, right after the if/else block containing the console.log(...data...) call:

ec2.describeInstances( function(err, data) {
  console.log("\nIn describe instances:\n");
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log("\n\n" + data + "\n\n"); // successful response
  context.done(null, 'Function Finished!');  
});