You should add this part to the article, so it's clearer what the problem is.
Can you also show how the timing of things would be different with an alternative implementation?
I'm guessing a solution/work around is to not return the new promise in each step, since you don't really care about the result. It looks like you only really care about the error?
In my example yes, but I kept it simple to easily reproduce the problem.
Many times however you do care about building a state, folding over the results ... e.g. if you have chunks of data read asynchronously from a file, you might want to gradually analyze it and produce some final result eventually.
Yes, a solution would be to not use return, but many times you need to return, since you need that value. But if you complicate the sample shown, then the origin of the leak gets confusing, so I guess it's a trade-off I haven't hit.
The only real use case for something like this (where it would be an actual problem) is an infinite chain of events, like an async message queue. I've used similar code for that before, without knowing of this memory leak. Letting it run forever in a node app would cause issues.
But now that we (soon) have async iterables it seems less like a problem. They fit much better in those situations, like reading a file and processing chunks of it. I guess promises aren't really designed to be used like this, and while it is a problem now, it's less likely to be one when we have alternatives.
What I'm describing is basically an async iterator and I think that even for iterators, it's useful to have a non-leaky implementation because you can then easily describe lazy stream transformations.
2
u/Gundersen Oct 11 '17
You should add this part to the article, so it's clearer what the problem is.
Can you also show how the timing of things would be different with an alternative implementation?
I'm guessing a solution/work around is to not return the new promise in each step, since you don't really care about the result. It looks like you only really care about the error?