1

I am trying to perform a GET call in typescript to various services and capture a value from their json response which will be passed in as a param in another function.

Through some online searching, I bumped into axios but am having a hard time wrapping my head around asynchronous apis and how to handle promises. Here is the code, that returns 'undefined' as an output.

function getVersion(url: string) {
let version;
let res = await axios.get(url)
  .then((response: { data: { buildInfo: { details: { version: any; }; }; }; }) => {
    version = response.data.buildInfo.details.version;
    return version;
  })
  .catch((error: any) => {
    console.log(error);
  });
return version;

}

I've also tried async/await but have trouble with unhandled promises. I don't need to use axios, any library will do as long as I can access the response to use in consequent functions.

1 Answers1

0

you can return a promise for getVersion()

async function getVersion(url: string) {
  let res = await axios.get(url)
  .then((response: { data: { buildInfo: { details: { version: any; }; }; }; }) => {
    let version = response.data.buildInfo.details.version;
    return new Promise((resolutionFunc) => { // return a promise
       resolutionFunc(version);
    });
  })
  .catch((error: any) => {
    console.log(error);
  });
  return res;
}

getVersion(url).then(res => {console.log(res)})  // use 

or you can just return the axios, beacuse axios will return a promise

async function getVersion(url: string) {
  let res = await axios.get(url)
  return res;
}

getVersion(url).then(res => {console.log(res)})  // use 
linchong
  • 485
  • 2
  • 4
  • I want to retrieve the json `version` value from the response because I am storing this value. I am going to make this call repetitively since I will be polling for version values and checking against the stored values. Can axios do this? The examples I have seen involve console.log but I want to be able to capture and use the json data for other functions and to store. – Carolyn Aquino Feb 09 '21 at 01:56
  • @Carolyn Aquino I use console.log to check the correctness of the return value, you can do anything with the return value – linchong Feb 09 '21 at 02:01
  • I tried the latter approach in this manner: async function getVersion(url: string) { let res = await axios.get(url) return res; } ----------------------------------------------------------------- let myMap = new Map(); for (var i = 0; i < endpoints.length; i++) { let url = 'http://' + endpoints[i].endpoint +'/status' getVersion(url).then(res => { myMap.set(endpoints[i].name, res.data.buildInfo.details.version); console.log(myMap);}) }. and I get a Unhandled Promise Warning – Carolyn Aquino Feb 09 '21 at 13:40