Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use fetch in while loop

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?

like image 811
krave Avatar asked Jul 10 '17 09:07

krave


People also ask

How do you store fetch data in a variable?

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.

How do I use fetch and then in JavaScript?

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.

Can we use while loop in JavaScript?

Loops can execute a block of code as long as a specified condition is true.

How do you wait for a fetch response?

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.


2 Answers

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.

like image 90
Mate Solymosi Avatar answered Oct 19 '22 02:10

Mate Solymosi


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

};
like image 29
Darkrum Avatar answered Oct 19 '22 01:10

Darkrum