newCoder
newCoder

Reputation: 45

Using axios.get inside a for loop

I have an array of links to get data from.How do i wait for it to complete the process and the get the data from within the axios.

function site1(url,arr){
        for(i=0;i<arr.length;i++){
              axios.get(url)
                  .then(response=>{
                    const $=cheerio.load(response.data);
                    //get desired data from site
                    //modify the array
                  }
    }    
 }

Now how do i make my code wait for this process to complete and get the modified arr out of it.

Upvotes: 0

Views: 1118

Answers (3)

M A Salman
M A Salman

Reputation: 3820

You can use axios.all.it expects an array of promises

Test below

//three urls
let promises=[],urls=["https://api.covid19api.com/country/NetherLands/status/deaths",
"https://api.covid19api.com/country/NetherLands/status/recovered",
"https://api.covid19api.com/country/NetherLands/status/active"];
urls.forEach( (url) => promises.push(axios.get(url))) 
axios.all(promises).then(axios.spread(function (res) {console.log(res);}));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Upvotes: 0

Max Starling
Max Starling

Reputation: 1037

You can try map an array to array of promises and await them with Promise.all()

const promises = arr.map(item => axios.get(item.url));

const result = await Promise.all(promises);
console.log(result); // [...]
/* or */

Promise.all(promises).then(result => {
  console.log(result); // [...]
});

Upvotes: 1

xdeepakv
xdeepakv

Reputation: 8125

Create promise and push in the array, then resolve all to get values.

function site1(url, arr) {
  let promises = [];
  for (i = 0; i < arr.length; i++) {
    promises.push(
      axios.get(url).then(response => {
        const $ = cheerio.load(response.data);
        return $;
      })
    );
  }
  return Promise.all(promises);
}
site1("https://google.com", [1, 2, 3, 4]).then(results => {
  console.log(results);
});

//Simple:

const urls = ["url1", "url2"];
const promises = urls.map(url => axios.get(url));
Promise.all(promises).then(results => {
  console.log(results);
});

Upvotes: 2

Related Questions