0

I'm very new to ES6 and JS world. I'm trying to create simple Utils method that will invoke the GET call using axios library and return the response.data as below:

AxiosUtils.js

const axios = require('axios');
const https = require('https');
const httpsAgent = new https.Agent({rejectUnauthorized: false});

class TestInvoker
{
    constructor(url,body,hostName,securityContext)
    {
        this.url = url;
        this.body = body;
        this.hostName = hostName;
        this.securityContext = securityContext;
    }

    invokeAgentGetCall()
    {
        let responseBody;

        axios.get(this.url,{
            httpsAgent:httpsAgent,
            headers:{
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Hostname": `${this.hostName}`,
            "prefer":"",
            "X-AMAZON-SECURITY-CONTEXT": JSON.stringify(this.securityContext),
            "AMAZON-Request-Id":'',
            "Access-Control-Allow-Origin": true
            }
        }).then((res) => {
          responseBody = res.data;
          console.log(responseBody);
          return responseBody;
        }).catch(error => {
            console.log(error);
        })
    }
   
}
module.exports = TestInvoker;

Calling the invokeAgentGetCall() method in another JS file as like below:

Test.js:

const TestInvoker = require("./AxiosUtils.js");

//This is public api for testing activity and no need any security header to call this get api
const result = new TestInvoker("https://jsonplaceholder.typicode.com/todos/1","","",""); 

console.log(result.invokeAgentGetCall());

Output:

node Test.js

undefined

{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }

When I print the responseBody inside that class it shows the proper response but when I return that object and tried to print it from test.js it shows 'undefined'.

Can anyone help me to resolve this?

ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84
  • You `return responseBody;` only from the `then` callback, the `invokeAgentGetCall` does not `return` anything. You should return the promise chain - and to log the result, you will then need to use `result.invokeAgentGetCall().then(console.log)` – Bergi May 19 '21 at 13:14
  • 1
    Hi, Unfortunately the question has been closed after I made up the solution for you.. So I am sharing the working example here https://codesandbox.io/s/distracted-sun-v8r8z .. Please look at the ```async/await``` in javascript and that is what you can implement as a solution.. – Maniraj Murugan May 19 '21 at 13:38

0 Answers0