Home > Software design >  Calling a function multiple times in a while loop
Calling a function multiple times in a while loop

Time:03-26

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, but I think my code is wrong. It calls only once, anyone correct me, please.

Here is my code :

const fetchData = async() => {
var data = [];
while(data.length == 0)
{
  data = await functionCall()
   if(data.length > 0)
    {
     break ;
    }
 }
}

CodePudding user response:

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.

CodePudding user response:

Try something like this.

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

CodePudding user response:

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();

  • Related