Comment

Comment by ajanuary

The verbosity comes because they are demonstrating both how to write the library code to support the feature, and how to consume it. But in reality a lot of the time someone else will have written the library code for you.

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);
parent ajanuary 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton