krave
krave

Reputation: 1909

How can I use fetch in while loop

My code is something like this:

var trueOrFalse = true;
while(trueOrFalse){
    fetch('some/address').then(){
        if(someCondition){
            trueOrFalse = false;
        }
    }
}

But I can not issue the fetch request. It seems like while loop is schedule many fetches into next tick. But never skip to next tick. How can I solve the problem?

Upvotes: 13

Views: 21055

Answers (4)

Darkrum
Darkrum

Reputation: 1373

Now with async/await we can use awesome while loops to do cool stuff.

var getStuff = async () => {

    var pages = 0;

    while(true) {

        var res = await fetch(`public/html/${pages ++}.html`);

        if(!res.ok) break; //Were done let's stop this thing

        var data = await res.text();

        //Do something with data

    };

    console.log("Look ma! I waited!"); //Wont't run till the while is done

};

Upvotes: 7

Peter B
Peter B

Reputation: 24147

The while loop fires off all the fetches before any one of them will reach the then(), so a while loop is incorrect here, even useless I would say.

You need to make the then() responsible for whether to continue fetching or not.

It also seems that your then()-syntax is wrong (maybe just an error editing the example). Furthermore you can omit the boolean helper variable (unless perhaps you need it in some other place).

function fetchUntilCondition(){
    fetch('some/address').then(function(response){
        if(!someCondition) {
           fetchUntilCondition(); // fetch again
        }
    });
}
fetchUntilCondition();

Upvotes: 2

Mate Solymosi
Mate Solymosi

Reputation: 5977

while(true) creates an infinite loop, which will attempt to call fetch infinitely many times within a single "tick". Since it never finishes issuing new fetch calls, it never gets to the next tick.

This function is very CPU-intensive and will probably lock up the entire page.


What's the solution?

What you are probably trying to do is keep fetching until the result satisfies some condition. You can achieve that by checking the condition in the then callback, and re-issuing the fetch if it is false:

var resultFound = false;

var fetchNow = function() {
  fetch('some/address').then(function() {
    if(someCondition) {
      resultFound = true;
    }
    else {
      fetchNow();
    }
  });
}

fetchNow();

This way, instead of

fetch!
fetch!
fetch!
fetch!
...

...the behavior is going to be

fetch!
  wait for response
  check condition
if false, fetch!
  wait for response
  check condition
if true, stop.

...which is probably what you expected.

Upvotes: 22

Manwal
Manwal

Reputation: 23816

while loop is sync where fetch is async in nature, so while won't wait for fetch async operation to complete and going to next iteration immediately.

You can achieve this synchronously like following:

function syncWhile(trueOrFalse){
    if(trueOrFalse) {
    fetch('some/address').then(){
        if(someCondition){
            trueOrFalse = false;
        }
        syncWhile(trueOrFalse);
    }
  }
}
syncWhile(true);

Upvotes: 4

Related Questions