Skip to content

Conversation

@Andarist
Copy link
Contributor

@Andarist Andarist commented Nov 29, 2024

Given that async functions flatten returned promises it's a fairly easy mistake to make to assume that try/catch/finally enclosing a returned promise can handle that as if return await p would be written:

declare function mayThrow(): Promise<number>

async function caller(): Promise<number> {
  try {
    return mayThrow()
  } catch (err) {
    // oops, this *won't* be executed
  }
}

For that reason, I think, it would be great if TS could suggest adding that "missing" await

I'm opening this PR as a draft proposal for this feature. It still requires some work to be finalized but it already shows nicely the idea. I can finish this after receiving positive feedback.

I understand this is on the verge of being a lint rule so I'd be fine with closing this for that reason

@typescript-bot typescript-bot added the For Uncommitted Bug PR for untriaged, rejected, closed or missing bug label Nov 29, 2024
@typescript-bot
Copy link
Collaborator

This PR doesn't have any linked issues. Please open an issue that references this PR. From there we can discuss and prioritise.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not gonna lie, those messages could use some improvement

if (canBeConvertedToAsync(node)) {
addConvertToAsyncFunctionDiagnostics(node, checker, diags);
}
if (isFunctionLikeDeclaration(node) && isAsyncFunction(node)) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: recheck the desired behavior for async generators and add related tests

async function outer() {
try {
return await (Math.random() > 0.5 ? inner() : 5);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should actually produce this:

Suggested change
return await (Math.random() > 0.5 ? inner() : 5);
return Math.random() > 0.5 ? await inner() : 5;

The current implementation is a draft and it's not yet fully implemented for more complex cases. The problem with it is that for the code like this:

return Math.random() > 0.5 ? await inner1() : inner2();

the compiler shouldn't produce smth like this

return await (Math.random() > 0.5 ? await inner1() : inner2());

but rather:

return Math.random() > 0.5 ? await inner1() : await inner2();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

Status: Not started

Development

Successfully merging this pull request may close these issues.

2 participants