Monday, May 20, 2024
103
rated 0 times [  105] [ 2]  / answers: 1 / hits: 18820  / 7 Years ago, mon, july 10, 2017, 12:00:00

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?


More From » ecmascript-6

 Answers
20

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.


[#57144] Friday, July 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;