Resource management

Isiah Meadows isiahmeadows at gmail.com
Tue Dec 27 16:25:11 UTC 2016


In [this GH issue in the async iteration proposal][1], I found that
the async iteration concept itself could theoretically be used for
resource management, such as in this example (copy/pasted from my
initial issue):

```js
const fsp = require("fs-promise")

async function *open(file, opts) {
    const fd = await fsp.open(file, opts)
    try { yield fd } finally { await fsp.close(fd) }
}

for await (const fd of open("/path/to/file", {mode: "r+"})) {
    const bit = await fsp.read(fd)
    // do other things...
}

// descriptor automatically closed, so no resource leaks!
```

It's neat and all, but we *really* should have something much better
than that. Maybe something like this?

```js
// Strict mode only
with (const fd = await open("/path/to/file", {mode: "r+"})) {
    const bit = await fsp.read(fd)
    // do other things...
}
```

(I'm not totally sure about what methods the closeable/etc. API or
protocol should use.)

[1]: https://github.com/tc39/proposal-async-iteration/issues/68

-----

Isiah Meadows
me at isiahmeadows.com


More information about the es-discuss mailing list