by ajanuary · 3y ago · 0 comments
In this (still contrived) example, we end up having to do nested try/finally blocks.
Before:
let totalSize = 0;
let fileListHandle;
try {
fileListHandle = await open("file-list.txt", "r");
for await (const line of fileListHandle.readLines()) {
let lineFileHandle;
try {
lineFileHandle = await open(lineFileHandle, "r");
totalSize += await lineFileHandle.read().bytesRead;
} finally {
await lineFileHandle?.close();
}
}
} finally {
await fileListHandle?.close();
}
console.log(totalSize);
After: let totalSize = 0;
try {
await using fileListHandle = getFileHandle("file-list.txt", "r");
for await (const line of fileListHandle.readLines()) {
await using lineFileHandle = getFileHandle(lineFileHandle, "r");
totalSize += await lineFileHandle.read().bytesRead;
}
}
console.log(totalSize); lineFileHandle = await open(lineFileHandle, "r");
should be lineFileHandle = await open(line, "r");
Same thing for the using version. let totalSize = 0;
const fileListHandle = await open("file-list.txt", "r");
try {
for await (const line of fileListHandle.readLines()) {
const lineFileHandle = await open(lineFileHandle, "r");
try {
totalSize += await lineFileHandle.read().bytesRead;
} finally {
await lineFileHandle.close();
}
}
} finally {
await fileListHandle.close();
}
console.log(totalSize);It’s possible that there are UI systems where this would work but not the ones you listed above.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
With this new using syntax, resources are disposed of when the object they are tied to goes out of _lexical scope_, which doesn’t need to worry about the runtime or object lifetimes at all. This example from the TC39 proposal makes it pretty clear:
function * g() {
using handle = acquireFileHandle(); // block-scoped critical resource
} // cleanup
{
using obj = g(); // block-scoped declaration
const r = obj.next();
} // calls finally blocks in `g`
https://github.com/tc39/proposal-explicit-resource-managemen...