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.
async and awaitInside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
For loop As in the above code the for loop is running for infinite times and printing the i value that is 10 infinitely. As above the loop is running infinite times because short int ranges is -32768 to 32767, so when i is the increment above to 32767 it becomes negative and hence the condition becomes always true.
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.
To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop. In this guide, you learn how async/await works and how it solves the problem of using promises in for loops.
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));
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With