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 |2 Answers
Reset to default 14How 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));
})();
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