r/javascript • • Oct 11 '17

JavaScript's Promise is Memory Unsafe

https://alexn.org/blog/2017/10/11/javascript-promise-memory-unsafe.html
70 Upvotes

77 comments sorted by

View all comments

0

u/[deleted] Oct 11 '17

[deleted]

-18

u/alexelcu Oct 11 '17

As I mentioned in the article, an implementation that doesn't leak is possible.

So obviously the assertion about creating an "infinitely long promise chain ... means nothing can be GCed" is false.

To see it in action, do this:

npm install funfix --save

And then:

import { Future } from "funfix"

function loop(n) {
  return Future.of(() => n).flatMap(i => {
    if (i % 1000 == 0) console.log(i)
    return loop(n + 1)
  })
}

loop(0).recover(console.error)

This code is doing exactly the same thing, but it doesn't leak.

This is sort of a Stockholm Syndrome btw :-)

0

u/[deleted] Oct 11 '17

[deleted]

-9

u/alexelcu Oct 11 '17

All loops in functional programming are expressed as tail recursions, or as folds that are implemented with tail recursions, because otherwise there's no way to express them. And classic loops are inadequate for expressing algorithms involving asynchronous calls, being error prone.

This is not a narrow, edge case, having started with lambda calculus in 1930. It's only an edge case when your tool of choice doesn't support it.

Hence my Stockholm Syndrome joke is really only a half joke ;-)

0

u/[deleted] Oct 11 '17

[deleted]

1

u/pier25 Oct 23 '17

It is an edge case to keep around a 2,000,000 promise long chain

I agree. Very few people will stumble upon that problem, if ever.

Whether the standard is properly designed to handle such an edge case is another story.