How to call a function repeatedly after it finishes?

131 Views Asked by At

I want to call a function main() which contains a lot of asynchronous db-connection calls. I want to call this function repeatedly after an iteration of main() gets finished.

How should I do that in Nodejs? I think there is some way to use promises over here to do this. But I am not able to think in the correct direction.

2

There are 2 best solutions below

0
On BEST ANSWER

Use Promise.all to wait for all promises to finish.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Afterwards you can call .then(main)

function main() {
  var promises = [];

  promises.push(...);
  promises.push(...);
  ...

  Promise.all(promises).then(main);
}
3
On

You could group all asynchronous promises into one promise object and execute your function again after all promises are met. More about promise grouping: Promise from an array of promises in NodeJS Deferred?

You shouldn't run your function again not considering promise completion, it could lead to strange behavior.