0

I am solving a question on hackerrank to print country name for the corresponding country code. I am getting the correct result in my console log statement but getting undefined in my output. The function is given below and i have commented the line on which I am getting undefined.

async function getCountryName(code) {

// write your code here
// API endpoint: https://jsonmock.hackerrank.com/api/countries?page=<PAGE_NUMBER>
for(var i =1 ;i<26;i++)
{
    const url = "https://jsonmock.hackerrank.com/api/countries?page=" + i;
https.get(url, resp => {
    let data = '';

    resp.on('data', (chunk) => {
        data += chunk;
    });

    resp.on('end',(chunk) => {
         let countries = JSON.parse(data).data;
         for(let info of countries) {
             const { alpha2Code } = info;
             if(alpha2Code.localeCompare(code)===0){
                 const { name } = info;
                 
                 console.log(name); //Getting the correct result here
                 return name; //here I am getting undefined
            
             };
          };
       });
     });
   }    
}

I am a beginner to javascript please help.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Rishav
  • 49
  • 9
  • The callback returning the value is not an async function. Can you point the exact place where you're receiving `undefined` from that callback function? – Teemu Jul 04 '20 at 19:58
  • You have gotten too far ahead of yourself doing all these requests in a loop without really understanding how to use `https.get()` for a single request. That `return` does not return to the outer function and does not break that outer loop either – charlietfl Jul 04 '20 at 20:04

0 Answers0