Resource management

Jordan Harband ljharb at gmail.com
Thu Dec 29 09:40:04 UTC 2016


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).

Assuming `fsp.open()` will always settle, but not assuming that `func()`
will, you'd need something more like this:
```js
async function open(file, opts, func) {
  const fd = await fsp.open(file, opts);
  const funcPromise = func(fd);
  return Promise.race([
    delay(30), // implementation of a function that returns a resolved
promise in 30s left to the user
    funcPromise,
  ]).finally(fd => fsp.close(fd)); // assuming the "finally" proposal is
available
}
```

On Wed, Dec 28, 2016 at 4:30 AM, Raul-Sebastian Mihăilă <
raul.mihaila at gmail.com> wrote:

> Such a protocol would make sense only if new specific syntax was added to
> the language. But is that really necessary when this can be implemented
> very easily without new syntax?
>
> ```js
> async function open(file, opts, func) {
>   const fd = await fsp.open(file, opts);
>
>   await func(fd);
>   await fsp.close(fd);
> }
>
> await open("/path/to/file", {mode: "r+"}, async function (fd) {
>   const bit = await fsp.read(fd);
> });
> ```
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20161229/84a35832/attachment-0001.html>


More information about the es-discuss mailing list