0

I want to get data from and array of urls using axios library

var axios = require('axios');

function askServers(urls){
    var index = 0;
    return axios.get(urls[index]).then(function(response){

      // expected result : "[{full_name: "John Doe", age : 20},{full_name: "John Boe", age : 51},...]"
      return JSON.parse(response.data); // return data without continuing to next url

    }).catch(function(err) { 
        if(urls.length>1){ //if error and urls array has more than 1 element, make request for the next url
            return askServers(urls.slice(1));
        }
        else{ //if array has one element only, return empty json array
            return JSON.parse("[]");
        }
    })
}

var urls = ["http://localhost:3001/getUsers","http://localhost:3002/getUsers","http://localhost:3004/getUsers"];

console.log(askServers(urls));

the last line returns Promise { <pending> }. Any idea how to solve this problem ?

Thanks

HKHAIT
  • 149
  • 2
  • 10
  • 2
    Replace with `askServers(urls).then(res => console.log(res));` – Weedoze Sep 01 '20 at 09:56
  • 2
    `askServers(urls).then(function(data) { console.log(data) })`. It's unlikely you'll need to use `JSON.parse()` since Axios usually takes care of that for you – Phil Sep 01 '20 at 09:57

0 Answers0