How can I use fetch during a loop
My code looks something like this:
var trueOrFalse = true;
while(trueOrFalse){
fetch('some/address').then(){
if(someCondition){
trueOrFalse = false;
}
}
}
But I cannot issue a fetch request. It seems that the while loop is the chart that many choose on the next tick. But never go to the next tick. How can I solve the problem?
source to share
while(true)
creates an infinite loop that will try to call fetch
infinitely many times in one tick . Since it never finishes issuing new calls fetch
, it never moves on to the next tick.
This feature is very CPU intensive and will probably block the entire page.
What solution?
What you are probably trying to do is keep the selection until the result satisfies some condition. You can achieve this by checking the condition in the callback then
and re-issuing fetch
if it is false
:
var resultFound = false;
var fetchNow = function() {
fetch('some/address').then(function() {
if(someCondition) {
resultFound = true;
}
else {
fetchNow();
}
});
}
fetchNow();
Thus, instead of
fetch! fetch! fetch! fetch! ...
... the behavior will be
fetch!
wait for response
check condition
if false, fetch!
wait for response
check condition
if true, stop.
... this is probably what you expected.
source to share
while
sync
, where it fetch
is async
in nature, so while
it will not wait for the operation fetch
async
to complete and go to the next iteration immediately.
You can achieve this synchronously as shown below:
function syncWhile(trueOrFalse){
if(trueOrFalse) {
fetch('some/address').then(){
if(someCondition){
trueOrFalse = false;
}
syncWhile(trueOrFalse);
}
}
}
syncWhile(true);
source to share
The while loop turns off all fetch before any of them reach then()
, so the while loop is wrong here, even useless, I would say.
You need to make then()
the continuation responsible or not.
It also seems that your then()
-syntax is wrong (it might just be an error editing the example). Alternatively, you can omit the boolean helper variable (if you probably don't need it elsewhere).
function fetchUntilCondition(){
fetch('some/address').then(function(response){
if(!someCondition) {
fetchUntilCondition(); // fetch again
}
});
}
fetchUntilCondition();
source to share