Nightcrawler
Nightcrawler

Reputation: 1051

How to call async Function until condition is true using javaScript?

I have such a problem, I am using API call which returns Fake store data, Everything works fine I am pushing received data into arr array, my aim is to call repeatCall() function until arr.length will be arr.length === 100, Also the problem is, sometimes I want to filter received data based on condition and then push it into arr array, What would be the optimal solution in this case?

let arr = [];
async function repeatCall() {
    const req = await fetch(`https://fakestoreapi.com/products`);
    const resp = await req.json();
    arr.push(...resp)
    console.log(arr.length)
}

  repeatCall()

Upvotes: 0

Views: 499

Answers (1)

M.Hassan Nasir
M.Hassan Nasir

Reputation: 851

Use an if condition on arr.length it will fetch api till the length is equal to 100.

let arr = [];
async function repeatCall() {
    const req = await fetch(`https://fakestoreapi.com/products`);
    const resp = await req.json();
    arr.push(...resp)
    console.log(arr.length)
    if(arr.length < 100){
              repeatCall();
    }
}

As for filtering the data before pushing it to array.

let arr = [];
    async function repeatCall() {
        const req = await fetch(`https://fakestoreapi.com/products`);
        const resp = await req.json();
        resp.foreach(item => {
           if(condition){
              arr.push(item);
           }   
           else{
              console.log("don't push")             
           }    
        })
       
        if(arr.length < 100){
                  repeatCall();
        }
        console.log(arr.length)
    }

Upvotes: 1

Related Questions