1

I am trying to invoke a rest API inside an API but it is not returning anything. So I am making a simple lambda which returns a JSON but getting a null value as a response.

var https = require('https');
var dt;
exports.handler = async (event, context) => {
      var data = '';

    return new Promise((resolve, reject) => {
      var params = {
                host: "cvwtzygw4a.execute-api.ap-south-1.amazonaws.com",
                path: "/test/first"
                };

        const req = https.request(params, (res) => {
          console.log('STATUS: ' + res.statusCode);
           res.setEncoding('utf8');
           res.o n('data', function(chunk) {
               data += chunk;
             });
         res.on('end', function() {
          console.log("DONE");

          console.log(data);
           dt = JSON.parse(data);
          console.log(dt);
         });


      resolve(dt);
    });

    req.on('error', (e) => {
      reject(e.message);
    });

    // send the request
    req.write('');
    req.end();
 });
};
Santosh Aryal
  • 1,276
  • 1
  • 18
  • 41
  • `resolve(dt)` will not wait for async calls. – AZ_ Jan 03 '20 at 11:00
  • you can use [request-promise](https://www.npmjs.com/package/request-promise) for invoking API's – AZ_ Jan 03 '20 at 11:01
  • Does this answer your question? [nodejs - How to promisify http.request? reject got called two times](https://stackoverflow.com/questions/38533580/nodejs-how-to-promisify-http-request-reject-got-called-two-times) – AZ_ Jan 03 '20 at 11:04
  • i am new to async programming can you provide the solution – Saurabh kapoor Jan 03 '20 at 11:09

1 Answers1

1

You should go through this article to understand how to use NodeJs promises in AWS Lambda. In this, the second solution addresses your use case.

To be specific to your code, I modified to make it very simple using the async/await syntax and the request-promise library.

const request = require('request-promise');
exports.handler = async (event, context) => {
    var data = '';

    try {
        data = await request.get('https://cvwtzygw4a.execute-api.ap-south-1.amazonaws.com/test/first');
        console.log('response received', res);
    } catch (error) {
        console.log('Error', error);
    }
    return data;
};

Following was the output:

START RequestId: 80d75f93-5fa6-1354-c22c-0597beb075e7 Version: $LATEST
2020-01-03T17:51:19.987Z        80d75f93-5fa6-1354-c22c-0597beb075e7    response received {
"basic" : {"name":"John","age":31,"city":"New York"}
}
END RequestId: 80d75f93-5fa6-1354-c22c-0597beb075e7
REPORT RequestId: 80d75f93-5fa6-1354-c22c-0597beb075e7  Init Duration: 907.81 ms        Duration: 1258.54 ms    Billed Duration: 1300 ms        Memory Size: 128 MB       Max Memory Used: 55 MB

"{\n\"basic\" : {\"name\":\"John\",\"age\":31,\"city\":\"New York\"}\n}"
Sarthak Jain
  • 2,048
  • 11
  • 19