I had the same problem and realized that programming in NodeJS is actually different from Python or Java as JavaScript based. I will try to use simple concepts, as there may be several new people who would be interested or might come to this question.
Take a look at the following code:
var http = require('http'); // (1) exports.handler = function(event, context) { console.log('start request to ' + event.url) http.get(event.url, // (2) function(res) { //(3) console.log("Got response: " + res.statusCode); context.succeed(); }).on('error', function(e) { console.log("Got error: " + e.message); context.done(null, 'FAILURE'); }); console.log('end request to ' + event.url); //(4) }
Whenever you call a method in an http packet (1), it is created as an event, and this event receives a separate event. The get (2) function is actually the starting point of this separate event.
Now the function in (3) will be executed in a separate event, and your code will continue to execute the path and will automatically go to (4) and end it, because there is nothing more to do.
But the event released in (2) is still being performed somewhere, and it will take its sweet time to complete it. Pretty strange, right ?. Well no, this is not so. This is how NodeJS works, and it's pretty important that you envelop this concept. This is where JavaScript Promises comes to the rescue.
Learn more about JavaScript Promises here . In a nutshell you will need JavaScript Promise to keep the execution of the embedded code and will not create new / additional threads.
Most common NodeJS packages have an accessible version of their Promised API, but there are other approaches, such as BlueBirdJS, that address a similar issue.
The code you wrote above can be easily rewritten as follows.
'use strict'; console.log('Loading function'); var rp = require('request-promise'); exports.handler = (event, context, callback) => { var options = { uri: 'https://httpbin.org/ip', method: 'POST', body: { }, json: true }; rp(options).then(function (parsedBody) { console.log(parsedBody); }) .catch(function (err) {
Please note that the above code will not work directly if you import it into AWS Lambda. For Lambda, you will also need to package modules with a code base.