简体   繁体   English

递归承诺链

[英]Recursive promise chain

im currently working on a project that uses a few microservices and one of them must do the same thing over and over again. 我目前正在使用几个微服务的项目中工作,其中一个必须一遍又一遍地做同样的事情。

The code looks like this: 代码如下:

refresh: function(){
   return somePromise
   .then(doA)
   .then(doB)
   .then(doC)
   .catch(error)
}

So currently another function calls this "refresh" function with setInterval every second. 因此,当前另一个函数每秒使用setInterval调用此“刷新”函数。

The problem is that because of the async nature of these calls in refresh method, some bugs appear. 问题是由于刷新方法中这些调用的异步特性,会出现一些错误。

I changed the code to call the 'refresh' method again recursively in the last '.then' statement and removed the setInterval. 我更改了代码,以在最后一个“ .then”语句中递归地再次调用“ refresh”方法,并删除了setInterval。

refresh: function(){
   return somePromise
   .then(doA)
   .then(doB)
   .then(doC)
   .then(refresh)
}

Nowthe bugs appear to be gone and everything works perfectly. 现在,这些错误似乎消失了,并且一切正常。 My question is: Is this a good practice? 我的问题是:这是一种好习惯吗? Are there any memory problems with calling the "refresh" method recursively in the last '.then' statement? 在最后一个“ .then”语句中递归调用“ refresh”方法是否存在任何内存问题?

Is this a good practice? 这是一个好习惯吗?

If you just want it to repeat whenever it finishes and make sure the next iteration doesn't start before the previous one finishes, this is a perfectly fine practice (much better than setInterval() ). 如果您只希望它在完成时重复一次,并确保下一个迭代不会在上一个迭代完成之前开始,那么这是一个很好的做法(比setInterval()更好)。 Your looping stops if there's a rejection anywhere so you may want to code what should happen with a .catch() . 如果在任何地方都存在拒绝,则循环将停止,因此您可能希望编写.catch()会发生的情况。

Are there any memory problems with calling the "refresh" method recursively in the last '.then' statement? 在最后一个“ .then”语句中递归调用“ refresh”方法是否存在任何内存问题?

No. There are not. 不是,没有。 Since .then() is always called asynchronously, the stack always gets to unwind and since you presumably have async operations in your chain, there should be time for normal garbage collection. 由于.then()始终是异步调用的,因此堆栈总是会解散,并且由于您的链中大概有异步操作,因此应该有时间进行正常的垃圾回收。

See Building a promise chain recursively in javascript - memory considerations for more discussion of memory consumption during the looping. 请参阅Javascript中的递归构建承诺链-内存注意事项,以了解有关循环期间内存消耗的更多信息。


FYI, this must be pseudo-code because a function defined as a property refresh: function() {} won't be directly callable with .then(refresh) . 仅供参考,这必须是伪代码,因为定义为属性refresh: function() {}将不能直接通过.then(refresh)调用。 So, I'm assuming you did that properly in your real code. 因此,我假设您在实际代码中正确地做到了。

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

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