Skip to content

Top Level Await #25988

Closed
Closed

Description

Search Terms

top level await

Suggestion

The ability to utilise await directly at the top level of a module or a script. Currently the compiler does not support this, though it is becoming increasing possible to accomplish it in certain runtimes.

Top level await is currently a Stage 2 TC39 proposal. (I was unable to find any tracking issue for implementation, therefore this issue)

There was this issue #20923, which was marked as a question, but really was this feature request.

Use Cases

There are many patterns the are emerging that require top level await, many which are documented in the TC39 Proposal. The current workaround that is seen a lot in the wild is wrapping an async iife. There are lots instances where the main thread of program wants to utilise await to load resources.

The value of having top level await in Node.js REPL and Chrome debugger is now allowed. There is an outstanding issue to allow it in ts-node.

I know the core team is really really adverse to implementing things that haven't reached Stage 3, but there are sufficient patterns in the wild that allow this and an increasing number for situations where it can be allowed, that allowing it under a flag feels like something that might be entertained until it is delivered under Stage 4. If we in user-land choose the potential 👣 🔫 at our own risk, so be it.

Examples

The following:

async function main() {
  const dynamic = await import('./dynamic-thing.mjs');
  const data = await fetch(dynamic.url);
  console.log(data);
}
main();

Could be rewritten as:

const dynamic = await import('./dynamic-thing');
const data = await fetch(dynamic.url);
console.log(data);

Checklist

Technically, this would allow syntax which would change the runtime behaviour of JavaScript and allows new expression level syntax which is currently not permitted (but specifically reserved by TC39 for this purpose).

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueES NextNew featurers for ECMAScript (a.k.a. ESNext)FixedA PR has been merged for this issueSuggestionAn idea for TypeScriptUpdate Docs on Next ReleaseIndicates that this PR affects docs

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions