Search code examples
javascriptwhile-loopes6-promise

How to have an async endless loop with Promises


I need to have an "endless" while-loop which has promises inside it. Here's some example code:

let noErrorsOccured = true

while (noErrorsOccured){
    someAsyncFunction().then(() => {
        doSomething();
    }).catch((error) => {
        console.log("Error: " + error);
        noErrorsOccured = false;
    });
}

function someAsyncFunction() {
    return new Promise ((resolve, reject) => {
        setTimeout(() => {
            const exampleBool = doSomeCheckup();
            if (exampleBool){
                resolve();
            } else {
                reject("Checkup failed");
            }
        }, 3000);
    });
}

So this while-loop should run endless, except an error occurs, then the while-loop should stop. How can I achieve this?

I hope you can understand what I mean and thanks in advance.


Solution

  • How can I achieve this?

    Not with a blocking loop since promises won't be able to settle. You can learn more about JavaScript's event loop on MDN.

    Instead, call the function again when the promise is resolved:

    Promise.resolve().then(function resolver() {
        return someAsyncFunction()
        .then(doSomething)
        .then(resolver);
    }).catch((error) => {
        console.log("Error: " + error);
    });