0
import fetch from "node-fetch";

const URL_API = `https://jsonmock.hackerrank.com/api/countries?`;
async function getResponse() {
  let response = await fetch(URL_API, {
    method: "GET",
    headers: {
      "Content-type": "application/json",
    },
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      // handle error
      console.error(`The unknown error has occurred: ${error}`);
    });
}

getResponse();

async function getCapitalCity(country) {
  const data = await response.json(); //error mentioned here
  for (let info in data) {
    console.log(info);
    if (info.name === country) {
      return info.capital;
    } else {
      return -1;
    }
  }
}

console.log(getCapitalCity("Afghanistan"));

working on retrieving a json object. I am trying to use the response object from getResponse() in getCapitalCity() based on country entered (string). My problem is knowing how to use the response in the second function. currently get a promise rejected reference error: response is not defined. thank you in advance.

Phil
  • 157,677
  • 23
  • 242
  • 245
Marco G
  • 11
  • 1
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Phil Apr 05 '22 at 07:10
  • Simply use `const getResponse = () => fetch(URL_API).then(r => r.ok ? r.json() : Promise.reject(r));` and `const data = await getResponse()` – Phil Apr 05 '22 at 07:13
  • I also suggest you have a close look at the format of the data in that API response. It doesn't seem compatible with how you're attempting to use it – Phil Apr 05 '22 at 07:19

1 Answers1

-1

I have reorganized Your code and added different loops.

const URL_API = `https://jsonmock.hackerrank.com/api/countries?`;

async function getResponse() {
  let response = await fetch(URL_API, {
    method: 'GET',
    headers: {
      'Content-type': 'application/json'
    }
  })
  try {
    return await response.json();
  } catch (error) {
    // handle error
    console.error(`The unknown error has occurred: ${error}`);
  }
}

getResponse();

async function getCapitalCity(country) {

  const dat = await getResponse();
  const capital = dat.data.filter((item) => item.name === country).map(item => item.capital);

  return capital;

}
getCapitalCity('Afghanistan').then(items => console.log('capital: ', items))
mac
  • 162
  • 1
  • 1
  • 11