Home > Software design >  Node.JS API call returns UNDEFINED
Node.JS API call returns UNDEFINED

Time:10-29

I am trying to make my first API call with NodeJS by using node-fetch, however I am getting UNDEFINED as error.

The call works great on my browser link, however with the code below, it returns undefined:

import fetch from 'node-fetch';

const latLongAirports = [{
        "name": "Madrid",
        "iata": "MAD",
        "lat": 40.49565434242003,
        "long": -3.574541319609411,
    },{
        "name": "Los Angeles",
        "iata": "LAX",
        "lat": 33.93771087455066,
        "long": -118.4007447751959,
    },{
        "name": "Mexico City",
        "iata": "MEX",
        "lat": 19.437281814699613,
        "long": -99.06588831304731,}
]

export function getTemperature(iata){
    let data = latLongAirports.find(el => el.iata === iata);
    var url = "http://www.7timer.info/bin/api.pl?lon="   data.long   "&lat="   data.lat   "&product=astro&output=json"
    console.log(url);
    async () =>{
        const response = fetch(url);
        const data2 = await response.json();
        console.log(data2);
    }
}

console.log(getTemperature('MEX'));

Any ideas why I am not getting the data?

CodePudding user response:

  • getTemperature() missing return statement
  • fetch() not awaited
  • you have constructed an async ()=>{} but never invoke it

Simply make getTemperature() become async and await to it, also await to fetch and return the result.

export async function getTemperature(iata){
    let data = latLongAirports.find(el => el.iata === iata);
    var url = "http://www.7timer.info/bin/api.pl?lon="   data.long   "&lat="   data.lat   "&product=astro&output=json"
    console.log(url);
    
    const response = await fetch(url);
    const data2 = await response.json();
    console.log(data2);
    return data2;
}

console.log(await getTemperature('MEX'));

CodePudding user response:

I suggest making the whole getTemperature function an async function. Also use a try ... catch block when await something.

export async function getTemperature(iata) {

  /* ... */
  
  try {
  
    const response = await fetch(url);
    const data2 = await response.json();
    return data2;
  
  } catch (ex) {
  
    throw ex;
  
  }

}

Now your getTemperature function will return a promise as well


// then/catch

getTemperature("MEX").then((result) => {
  console.log(result);
})
.catch((error) => {
  console.log(error.message);
});


// or async/await

( async function () {
  
  try {
    const result = await getTemperature("MEX");
    console.log(result);
  } catch (ex) {
    console.log(ex.message);
  }

})();
  
  • Related