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?
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
The fetch() method requires one parameter, the URL to request, and returns a promise. Syntax: fetch('url') //api for the get request . then(response => response.
Loops can execute a block of code as long as a specified condition is true.
There are two ways to wait for fetch() : We can use then , and manipulate the response of our fetch() within then() . We can use await , and wait for the fetch to return before using its contents.
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.
Now with async/await we can use awesome while loops to do cool stuff.
var getStuff = async () => {
var pages = 0;
while(true) {
var res = await fetch(`public/html/${pages ++}.html`);
if(!res.ok) break; //Were done let's stop this thing
var data = await res.text();
//Do something with data
};
console.log("Look ma! I waited!"); //Wont't run till the while is done
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With