Typescript: Auto-insert `await` for property accesses on Promise

Created on 18 May 2019  路  10Comments  路  Source: microsoft/TypeScript

async function foo(x: Promise<string>) {
  x./**/
}

Go to the /**/ marker and request completions.

The proposal here is that all the completions for string should show up. When the user selects a string member, we should automatically await the value, so selecting toLowerCase changes the code to (await x).toLowerCase.

Completion Lists Moderate Fix Available Suggestion

Most helpful comment

This seems like a good idea but should only be done inside async functions if possible. In the example above, the function is not async so adding an await there would make the code invalid.

All 10 comments

This seems like a good idea but should only be done inside async functions if possible. In the example above, the function is not async so adding an await there would make the code invalid.

Yes, thank you, that was one of the subtler points I forgot to add to this issue. It would be incredibly annoying/unsafe otherwise.

Something else I just thought of: since this would be done via autocompletion, the feature probably shouldn't get any ideas about automatically converting the function to async - doing so is a breaking change in most cases since it forces the function into returning a promise.

Spoke with @littledan today, and once top-level await lands, we should consider doing this at the top level based on target and module options.

Related: #30646

/cc @bterlson: Thoughts on this (and the work done already at #32101) as a partial solution for #30646? Personally, I鈥檇 still like to surface a quick fix and make sure we have a really good diagnostic message in addition to this, but I think completions are a good first line of defense for the last bullet point you mentioned:

  • The target of a member expression and T has the member (or maybe the property name is not in Promise).

I like it a lot, personally. Incrementally addressing the various bullets is fine by me, and I think this is probably one of the biggest rocks.

The reason I put this proposal together was because when I spoke to @jonathandturner, I realized that better error messages (as in #30646) would only help TypeScript users, but would not help JavaScript users who aren't using type-checking.

Another quick fix is better, the current completion behavior seems cannot add async modifier simply as far as I know

a suggestion: add a new keyword to a function and translate to js with await all variables.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  路  3Comments

weswigham picture weswigham  路  3Comments

uber5001 picture uber5001  路  3Comments

dlaberge picture dlaberge  路  3Comments

siddjain picture siddjain  路  3Comments