Resource management

Jamesernator thejamesernator at gmail.com
Fri Dec 30 04:05:58 UTC 2016


The `for` loop approach works for synchronous resources as well 
actually, there's nothing special about those `await`ed things e.g.

```js
const fs = require('fs')

function* open(file, opts) {
     const fd = fs.openSync(file, opts)
     try { yield fd } finally { fs.closeSync(fd) }
}

for (const fd of open("/path/to/file", {mode: "r+"})) {
     const bit = fs.readSync(fd)
     ...
}
```

I can definitely imagine a Python-esque `with` statement though (perhaps 
with `Symbol.open/Symbol.close`) then you just use something like 
Python's contextlib 
(https://docs.python.org/3.7/library/contextlib.html) utility functions 
for converting generator based resources to `Symbol.open/Symbol.close`.

For now though the `for` loop approach is a relatively good workaround 
(as `next/return` effectively emulate Python's `__enter__/__exit__`).


On 30/12/16 04:17, Isiah Meadows wrote:
> But keep in mind it still doesn't cover two key issues:
>
> 1. Synchronous resources do in fact exist (primarily in Node). You
> need both for it to be effective.
> 2. Your suggestion isn't composable at all (like nearly every other
> callback-driven API), and it prevents returning from inside the block
> without the use of exceptions.
> -----
>
> Isiah Meadows
> me at isiahmeadows.com
>
>
> On Thu, Dec 29, 2016 at 9:05 AM, Raul-Sebastian Mihăilă
> <raul.mihaila at gmail.com> wrote:
>> I agree, but note that a resolved promise is not the same as a fulfilled
>> promise (https://tc39.github.io/ecma262/#sec-promise-objects).
>>
>> On Thu, Dec 29, 2016 at 11:40 AM, Jordan Harband <ljharb at gmail.com> wrote:
>>> You'd need to wrap the body of your `open` function in a try/finally, and
>>> do the `fsp.close` in the `finally` block - but otherwise that would
>>> certainly work, provided that the promise returned from `func` did actually
>>> settle (resolve or reject).
>>>
>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



More information about the es-discuss mailing list