简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM