13

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?

5
  • I will solve your problem if you post a jsfiddle Commented Jul 10, 2017 at 9:28
  • 5
    This sounds very much like an XY Problem Commented Jul 10, 2017 at 9:29
  • use setTinterval() instead of a while loop. Commented Jul 10, 2017 at 9:31
  • 1
    @ChrisG my money is on stackoverflow.com/questions/14220321/… Commented Jul 10, 2017 at 9:38
  • Thank you guys. Very impressive answers. Will generator do any help in this scene? Commented Jul 10, 2017 at 9:47

4 Answers 4

22

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.

Sign up to request clarification or add additional context in comments.

2 Comments

but if the condition won't be met within a finite number of loops, won't we risk in stack overflow?
7

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

};

Comments

4

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.