-1

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.

skjindal93
  • 706
  • 1
  • 16
  • 34
  • I think a better way would be to use a promise in main() function and after that promise gets resolved call main() again. But how to do that repeatedly – skjindal93 Jun 10 '15 at 14:54
  • But don't you have multiple promises? It's trivial if you have only one, you just call main at the end of your promise callback. – Shashank Jun 10 '15 at 14:55
  • 1
    Since it is async code, you will have to show us the actual async code so we can advise you more specifically. Generic questions like this without any actual code require people to provide generic answers that attempt to "guess" what you're actually doing and are rarely as targeted as answers can be if you show us your actual code. – jfriend00 Jun 10 '15 at 16:14

2 Answers2

1

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);
}
Tesseract
  • 8,049
  • 2
  • 20
  • 37
0

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.

Community
  • 1
  • 1
SzybkiSasza
  • 1,591
  • 12
  • 27