How can I use fetch in while loop

后端 未结 4 1472
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题