Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
mariushab Avatar asked Oct 06 '16 11:10

mariushab


People also ask

Can we use async with promises?

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.

Which loop promises to execute for infinite no of times?

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.

Are promises executed asynchronously?

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.

Can we use promise in for loop?

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.


2 Answers

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);
});
like image 149
Felix Kling Avatar answered Oct 10 '22 10:10

Felix Kling


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));
})();
like image 35
user1428570 Avatar answered Oct 10 '22 11:10

user1428570