简体   繁体   English

函数完成后如何重复调用?

[英]How to call a function repeatedly after it finishes?

I want to call a function main() which contains a lot of asynchronous db-connection calls.我想调用一个包含大量异步数据库连接调用的函数 main()。 I want to call this function repeatedly after an iteration of main() gets finished.我想在 main() 的迭代完成后重复调用这个函数。

How should I do that in Nodejs?我应该如何在 Nodejs 中做到这一点? I think there is some way to use promises over here to do this.我认为有一些方法可以在这里使用 Promise 来做到这一点。 But I am not able to think in the correct direction.但我无法朝着正确的方向思考。

Use Promise.all to wait for all promises to finish.使用 Promise.all 等待所有承诺完成。

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

Afterwards you can call .then(main)之后你可以调用.then(main)

function main() {
  var promises = [];

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

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

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?有关承诺分组的更多信息: 来自 NodeJS 中的承诺数组的承诺延迟?

You shouldn't run your function again not considering promise completion, it could lead to strange behavior.你不应该在不考虑承诺完成的情况下再次运行你的函数,它可能会导致奇怪的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM