-
Notifications
You must be signed in to change notification settings - Fork 37
Description
Following a suggestion by @littledan to post feedback here - some things we've noticed building and maintaining Promise.using
for bluebird and discussing the topic:
- Resource acquisition is almost always async
- Resource acquisition is considerably harder with multiple resources
- Resource release is sometimes synchronous
- It is important to deal with the case of failure to acquire one out of many resources
Let's try the absolute simplest case: I want to open two files and copy one to the other. Let's assume an open
async method, and a utils.copy
async method. Let's assume either opening or writing to the file can throw:
// no exception handling, this is the most basic case
async function copy(first, second) {
let firstFile = await open(first);
let otherFile = await open(second);
await utils.copyTo(first, second);
await close(firstFile);
await close(secondFile);
}
Now, let's write it with the syntax from this proposal:
async function copy(first, second) {
using(let firstFile = await open(first), otherFile = await open(second)) {
await utils.copyTo(first, second);
}
}
This is much nicer syntax! but if I understand correctly in this case if the second open
rejects the exception is outside the scope of the using (please do correct me if I'm misunderstanding). This means that since the object with Symbol.dispose
didn't get to the using
yet if one resource was acquired but not yet assigned to the variable declared in that scope.
By the way regarding the prior art: Python solves this with the new-ish async with
syntax. I have asked for the help of the proposal author it for discussing the resource management story for Deno and he agreed to help. I can gladly point him here if you'd like.
It is great to see that you have Symbol.asyncDispose
. I'm not sure how the fs.promises examples work (does using
in an async function implicitly await? fs.promise.open returns a promise and not a resource) but would love to collaborate from the Node.js side in order to help.