How can I use fetch in while loop

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

提交回复
热议问题