Reputation: 390
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.
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.
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?
Upvotes: 0
Views: 365
Reputation: 707158
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()
). Your looping stops if there's a rejection anywhere so you may want to code what should happen with a .catch()
.
Are there any memory problems with calling the "refresh" method recursively in the last '.then' statement?
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.
See Building a promise chain recursively in javascript - memory considerations for more discussion of memory consumption during the looping.
FYI, this must be pseudo-code because a function defined as a property refresh: function() {}
won't be directly callable with .then(refresh)
. So, I'm assuming you did that properly in your real code.
Upvotes: 3