tc39 / proposal-explicit-resource-management

ECMAScript Explicit Resource Management
https://arai-a.github.io/ecma262-compare/?pr=3000
BSD 3-Clause "New" or "Revised" License
725 stars 29 forks source link

What happens if the object escapes? #161

Open Lexicality opened 1 year ago

Lexicality commented 1 year ago

I'm assuming this should have an obvious answer but I can't see one in the README.

If I have

function foo() {
    using reader = stream.getReader();
    return () => reader.read();
}

what happens if I call foo()()?

NWYLZW commented 1 year ago

I think it should not be allowed to hijack variables declared by using through closures.

rbuckton commented 1 year ago

@Lexicality:

what happens if I call foo()()?

It depends on the behavior of reader.read(). In this example, reader would be closed as soon as foo() returns. Assuming read() requires an open stream, I would expect reader.read() would throw an exception when you call the resulting arrow function.


@NWYLZW:

I think it should not be allowed to hijack variables declared by using through closures.

This was discussed in #97 and in plenary. To avoid this would require re-entering TDZ, and implementers were concerned about the impact a new TDZ would cause. In addition, a well-written disposable resource needs to defend against using that resource when it is in an unusable state, since those resources could be created without using when composing multiple resources.

There are also valid use cases for being able to access the resource after it has been disposed, such when the resource was used as a key in a Map. Even after the resource is disposed you may want to remove the key.

Lexicality commented 1 year ago

@rbuckton ok so the answer is that the object gets disposed of no matter what.

I think it would be handy to call this out explicitly in the readme? It makes sense that closure lifetimes are ignored but it's not always obvious with these things