How can I use fetch in while loop

后端 未结 4 1570
名媛妹妹
名媛妹妹 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: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();
    

提交回复
热议问题