How can I use fetch in while loop

Viewed 17207

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?

4 Answers

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

};
Related