Darshan
Darshan

Reputation: 122

Calling a function multiple times in a while loop

I am trying to get data from a function call and I am keeping it in a while loop so the function will be called again and again if data is not received. What I meant with the data is the data1,data2 and data3 arrays that I have returned from the getData function should be populated and not have a null value. But I am not able to find the solution.

Here is my code :

router.get('/someurl' , async(req,res) => {
let data = [];
while(data.length == 0)
{
  data = await functionCall()
  console.log(data)
   }
})

And here is the format of my functionCall code :

const unirest = require("unirest");
const cheerio = require('cheerio')





const getData = async() => {
   const data1 = [] , data2 = [] , data3 = [] ;
   try {
   const response = await unirest
   .get('url')
   .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
   .proxy("proxy")
   const $ = cheerio.load(response.body)
   $('hided').each((i,el) =>
   {
         data1[i] = $(el)
         .find('hided')
         .text()
         data2[i] = $(el)
         .find('hided')
   })
   $('hided').each((i,el) =>
   {
         data3[i] = $(el)
         .find('hided')
         .text()
   })
    if(data1.length && data2.length && data3.length))
    {
      return [data1 , data2 , data3]
    }
   }
      catch(error)
      {
         console.log("Error" , error);
      }
      return [];
      }
 
 
module.exports =  getData

Upvotes: -1

Views: 1655

Answers (3)

Andy
Andy

Reputation: 63587

Assuming that fetchData is an API call there's no reason to initially define data. You can just log the results of calling that API until the results are an empty array.

const data = [1, 2, 3, 4];

// A simple API that returns a reduced array
// on every call
function mockApi() {
  return new Promise(res => {
    setTimeout(() => {
      res([...data]);
      data.shift();
    }, 1000);
  });
}

// Call the API, and if the the response
// has zero length log "No data" otherwise
// log the data, and call the function again.
async function fetchData() {
  const data = await mockApi();
  if (!data.length) {
    console.log('No data');
  } else {
    console.log(data);
    fetchData();
  }
}

fetchData();

Upvotes: 0

Shivansh Verma
Shivansh Verma

Reputation: 138

Try something like this.

const fetchData = async ()=>{
data = await functionCall()
if(data.length==0){
fetchData()
}else{
return}
}

Upvotes: 0

Cheng Adrian
Cheng Adrian

Reputation: 177

Firstly remove the if statement, as it is literally what the while loop is doing. then remove await, as this is not in an async function, and it will make an error.

Upvotes: 0

Related Questions