Skip to content

await using hides potential unhandled promises. #55001

@lukiano

Description

@lukiano

Bug Report

See explanation below the code.

🔎 Search Terms

await using disposable

🕗 Version & Regression Information

5.2 beta

💻 Code

(Symbol as any).dispose ??= Symbol("Symbol.dispose");
(Symbol as any).asyncDispose ??= Symbol("Symbol.asyncDispose");

import {promisify} from "util";
const delay = promisify(setTimeout);

class Resource {
  constructor(public readonly path: string) {}
  async [Symbol.asyncDispose]() {
    await delay(500);
    console.log('closed ' + this.path);
  }
}

class Boom extends Error {
  constructor() {
    super("Boom!");
  }
}

async function main() {
  await using file = await new Resource("thefile.txt");
  console.log(file.path);
  return Promise.reject(new Boom());
}

try {
  await main();
} catch (err) {
  console.log(`All good. Caught ${err.message}`);
}

🙁 Actual behavior

Boom [Error]: Boom!
    at main (file:///Users/luciano/git/ts-using/lib/index.mjs:70:31)
    at async file:///Users/luciano/git/ts-using/lib/index.mjs:83:5

The boom error is thrown due to being unhandled.

Explanation

My understanding is that this is happening due to return Promise.reject(new Boom()); returning a rejected promise, and the delay (with setTimeout) in the disposable function. The delay makes the rejected promise be seen and thrown.

It would be similar if the delay were in a finally section. However, the disposable function could be in an object within a library and thus not easily seen by users.

🙂 Expected behavior

thefile.txt
closed thefile.txt
All good. Caught Boom!

Caveat

The boom error should have been caught.

It could be that this isn't a bug, but working as expected. If so, let's consider making it clear in the documentation (e.g. use throw or return await Promise.reject()

Metadata

Metadata

Assignees

Labels

DocsThe issue relates to how you learn TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions