简体   繁体   中英

Node.js How to retrieve data from http.get response

I am doing some practice in node.js. In this exercise I been asked to find a country name through a GET Http Request to an endpoint passing a page integer as a parameter. Where the important response structs are these {page, total_pages, data}.

page is the current page,

total_pages is the last page,

data is an array of 10 country object.

In getCountryName func I am able to retrieve the right answer only if the answer is on the 1st page, the 1 iteration of the loop. So, why the loop only happens once? Aditional, I wanted to retrieve the total_pages to replace the hardcode '25' value but I do not figure it out how to return it along with the search.

Any hint you wanna give me? The whole problem is in getCountryCode func.

'use strict';

const { Console } = require('console');
const https = require('https');

function makeRequest(page){    
    return new Promise(resolve => {
        let obj='';
        https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
            let data ='';

            res.on('data',function(chunk){
                data+=chunk;
            });

            res.on('end',function(){
                obj=JSON.parse(data);
                resolve(obj);
            });
        });
    });
}


async function getCountryName(code) {          
    var res = '';
    var pages = 25;
    var i = 1;    
    while(i <= pages && res == ''){
        console.log(i);
        res = makeRequest(i)
            .then(data => {
                let f = ''
                let p = data['total_pages'];
                let search = data['data'].find(o => o.alpha3Code === code);   
                f = search != null ? search['name'] : f;
                return f;
            }); 
        i++;
    }
   return res;
}

async function main() {
  const name = await getCountryName('ARG');
  console.log(`${name}\n`);
}

main();

Without modifying your code too much, this is how you do it:

'use strict';

const { Console } = require('console');
const https = require('https');

function makeRequest(page){    
    return new Promise(resolve => {
        let obj='';
        https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
            let data ='';

            res.on('data',function(chunk){
                data+=chunk;
            });

            res.on('end',function(){
                obj=JSON.parse(data);
                resolve(obj);
            });
        });
    });
}


async function getCountryName(code) {          
    const pages = 25;
    var i = 1;  
    let f = null  
    while(i <= pages && f === null){
        console.log(i);
        const data = await makeRequest(i) // put in try/catch   
        const p = data['total_pages'];
        const search = data['data'].find(o => o.alpha3Code === code);   
        f = search !== null ? search['name'] : null;
        i++;
    }
   return res;
}

async function main() {
  const name = await getCountryName('ARG');
  console.log(`${name}\n`);
}

main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM