admin管理员组

文章数量:1221319

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.

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.

Share Improve this question edited Apr 3, 2020 at 0:19 mariushab asked Oct 6, 2016 at 11:27 mariushabmariushab 1131 gold badge1 silver badge8 bronze badges 2
  • 1 Promise reactions (calling fulfilled or rejection handlers) are executed asynchronously after a a thread causing them to be executed has completed. The first while loop is an infinite blocking loop, creating an infinite number of promises that never get settled because timeout call backs never occur :D Possibly you want a timeout or interval timer that that waits 3 seconds after a previous the promise created for an asynchronous check up becomes settled before running another check? – traktor Commented Oct 6, 2016 at 11:40
  • The problem is that i don't really know how long it takes for my promise to resolve, I only used setTimeout() to clarify my example. But Felix Kling's solution works perfectly, so there is no need for an other solution, but thanks anyway :) – mariushab Commented Oct 6, 2016 at 12:18
Add a comment  | 

2 Answers 2

Reset to default 14

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);
});

This is what worked for me (based on discussion here: https://github.com/nodejs/node/issues/6673 ) in NodeJS:

async function run(){
  // Do some asynchronous stuff here, e.g.
  await new Promise(resolve => setTimeout(resolve, 1000));
}

(function loop(){
   Promise.resolve()
     .then(async () => await run())
     .catch(e => console.error(e))
     .then(process.nextTick(loop));
})();

本文标签: javascriptHow to have an async endless loop with PromisesStack Overflow