How can I use fetch in while loop

后端 未结 4 1466
名媛妹妹
名媛妹妹 2021-02-09 05:52

My code is something like this:

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


        
相关标签:
4条回答
  • 2021-02-09 06:34

    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);
    
    0 讨论(0)
  • 2021-02-09 06:47

    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
    
    };
    
    0 讨论(0)
  • 2021-02-09 06:52

    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.

    0 讨论(0)
  • 2021-02-09 06:53

    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();
    
    0 讨论(0)
提交回复
热议问题