• This repository has been archived on 29/Aug/2021
  • Stars
    star
    1,083
  • Rank 42,742 (Top 0.9 %)
  • Language
    HTML
  • License
    Apache License 2.0
  • Created almost 7 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

top-level `await` proposal for ECMAScript (stage 4)

ECMAScript proposal: Top-level await

Champions: Myles Borins, Yulia Startsev.

Authors: Myles Borins, Yulia Startsev, Daniel Ehrenberg, Guy Bedford, Ms2ger, and others.

Status: Stage 4

Synopsis

Top-level await enables modules to act as big async functions: With top-level await, ECMAScript Modules (ESM) can await resources, causing other modules who import them to wait before they start evaluating their body.

Motivation

Limitations on IIAFEs

With await only available within async functions, a module can include an await in the code that executes at startup by factoring that code into an async function:

// awaiting.mjs
import { process } from "./some-module.mjs";
let output;
async function main() {
  const dynamic = await import(computedModuleSpecifier);
  const data = await fetch(url);
  output = process(dynamic.default, data);
}
main();
export { output };

This pattern can also be immediately invoked. You could call this an Immediately Invoked Async Function Expression (IIAFE), as a play on IIFE idiom.

// awaiting.mjs
import { process } from "./some-module.mjs";
let output;
(async () => {
  const dynamic = await import(computedModuleSpecifier);
  const data = await fetch(url);
  output = process(dynamic.default, data);
})();
export { output };

This pattern is appropriate for situations where loading a module is intended to schedule work that will happen some time later. However, the exports from this module may be accessed before this async function completes: If another module imports this one, it may see output as undefined, or it may see it after it's initialized to the return value of process, depending on when the access occurs! For example:

// usage.mjs
import { output } from "./awaiting.mjs";
export function outputPlusValue(value) { return output + value; }

console.log(outputPlusValue(100));
setTimeout(() => console.log(outputPlusValue(100), 1000);

Workaround: Export a Promise to represent initialization

In the absence of this feature, it's possible to export a Promise from a module, and wait on that to know when its exports are ready. For example, the above module could be written as:

// awaiting.mjs
import { process } from "./some-module.mjs";
let output;
export default (async () => {
  const dynamic = await import(computedModuleSpecifier);
  const data = await fetch(url);
  output = process(dynamic.default, data);
})();
export { output };

Then, the module could be used as:

// usage.mjs
import promise, { output } from "./awaiting.mjs";
export function outputPlusValue(value) { return output + value }

promise.then(() => {
  console.log(outputPlusValue(100));
  setTimeout(() => console.log(outputPlusValue(100), 1000);
});

However, this leaves us with a number of problems still:

  • Everyone has to learn about a particular protocol to find the right Promise to wait on the module being loaded
  • If you forget to apply the protocol, things might "just work" some of the time (due to the race being won in a certain way)
  • In a deep module hierarchy, the Promise needs to be explicitly threaded through each step of the chain.

For example, here, we waited on the promise from "./awaiting.mjs" properly, but we forgot to re-export it, so modules that use our module may still run into the original race condition.

Avoiding the race through significant additional dynamism

To avoid the hazard of forgetting to wait for the exported Promise before accessing exports, a module could instead export a Promise which resolves to an object which contains exports

// awaiting.mjs
import { process } from "./some-module.mjs";
export default (async () => {
  const dynamic = await import(computedModuleSpecifier);
  const data = await fetch(url);
  const output = process(dynamic.default, data);
  return { output };
})();
// usage.mjs
import promise from "./awaiting.mjs";

export default promise.then(({output}) => {
  function outputPlusValue(value) { return output + value }

  console.log(outputPlusValue(100));
  setTimeout(() => console.log(outputPlusValue(100), 1000);

  return { outputPlusValue };
});

It's unclear whether this pattern has caught on, but it's sometimes recommended in StackOverflow to people who face these sorts of issues.

However, this pattern has the undesirable effect of requiring a broad reorganization of the related source into more dynamic patterns, and placing much of the module body inside the .then() callback in order to use the dynamically available imports. This represents a significant regression in terms of static analyzability, testability, ergonomics and more, compared to ES2015 modules. And when you run into a deep dependency which needs to await, you need to reorganize all dependent modules to use this pattern.

Solution: Top-level await

Top-level await lets us rely on the module system itself to handle all of these promises, and make sure that things are well-coordinated. The above example could be simply written and used as follows:

// awaiting.mjs
import { process } from "./some-module.mjs";
const dynamic = import(computedModuleSpecifier);
const data = fetch(url);
export const output = process((await dynamic).default, await data);
// usage.mjs
import { output } from "./awaiting.mjs";
export function outputPlusValue(value) { return output + value }

console.log(outputPlusValue(100));
setTimeout(() => console.log(outputPlusValue(100), 1000);

None of the statements in usage.mjs will execute until the awaits in awaiting.mjs have had their Promises resolved, so the race condition is avoided by design. This is an extension of how, if awaiting.mjs didn't use top-level await, none of the statements in usage.mjs will execute until awaiting.mjs is loaded and all of its statements have executed.

Use cases

When would it make sense to have a module which waits on an asynchronous operation to load? This section gives some examples.

Dynamic dependency pathing

const strings = await import(`/i18n/${navigator.language}`);

This allows for Modules to use runtime values in order to determine dependencies. This is useful for things like development/production splits, internationalization, environment splits, etc.

Resource initialization

const connection = await dbConnector();

This allows Modules to represent resources and also to produce errors in cases where the Module will never be able to be used.

Dependency fallbacks

let jQuery;
try {
  jQuery = await import('https://cdn-a.com/jQuery');
} catch {
  jQuery = await import('https://cdn-b.com/jQuery');
}

WebAssembly Modules

WebAssembly Modules are "compiled" and "instantiated" in a logically asynchronous way, based on their imports: Some WebAssembly implementations do nontrivial work at either phase, which is important to be able to shunt off into another thread. To integrate with the JavaScript module system, they will need to do the equivalent of a top-level await. See the WebAssembly ESM integration proposal for more details.

Semantics as desugaring

Currently, a module waits for all of its dependencies to execute all of their statements before the import is considered finished, and the module's code can run. This proposal maintains this property when introducing await, : dependencies still execute through to the end, even if you need to wait for that execution to finish asynchronously. One way to think of this is as if each module exported a Promise, and after all the import statements, but before the rest of the module, the Promises are all awaited:

import { a } from './a.mjs';
import { b } from './b.mjs';
import { c } from './c.mjs';

console.log(a, b, c);

would be roughly equivalent to

import { promise as aPromise, a } from './a.mjs';
import { promise as bPromise, b } from './b.mjs';
import { promise as cPromise, c } from './c.mjs';

export const promise = Promise.all([aPromise, bPromise, cPromise]).then(() => {

console.log(a, b, c);

});

Modules a.mjs, b.mjs, and c.mjs would all execute in order up until the first await in each of them; we then wait on all of them to resume and finish evaluating before continuing.

FAQ

Isn't top-level await a footgun?

If you have seen the gist you likely have heard this critique before.

Some responses to some of the top concerns here:

Will top-level await cause developers to make their code block longer than it should?

It's true that top-level await gives developers a new tool to make their code wait. Our hope is that proper developer education can ensure that the semantics of top-level await are well-understood, so that people know to use it just when they intend that importers should block on it.

We've seen this work well in the past. For example, it's easy to write code with async/await that serializes two tasks that could be done in parallel, but a deliberate developer education effort has popularized the use of Promise.all to avoid this hazard.

Will top-level await encourage developers to use import() unnecessarily, which is less optimizable?

Many JavaScript developers are learning about import() specifically as a tool for code splitting. People are becoming aware of the relationship between bundling and multiple requests, and learning how to combine them for good application performance. Top-level await doesn't really change the calculus--using import() from a top-level await will have similar performance effects to using it from a function. As long as we can tie top-level await's educational materials into the existing knowledge of that performance tradeoff, we hope to be able to avoid counterproductive increases in the use of import().

What exactly is blocked by a top-level await?

When one module imports another one, the importing module will only start executing its module body once the dependency's body has finished executing. If the dependency reaches a top-level await, that will have to complete before the importing module's body starts executing.

Why doesn't top-level await block the import of an adjacent module?

If one module wants to declare itself dependent on another module, for the purposes of waiting for that other module to complete its top-level await statements before the module body executes, it can declare that other module as an import.

In a case such as the following, the printed order will be "X1", "Y", "X2", because importing one module "before" another does not create an implicit dependency.

// x.mjs
console.log("X1");
await new Promise(r => setTimeout(r, 1000));
console.log("X2");
// y.mjs
console.log("Y");
// z.mjs
import "./x.mjs";
import "./y.mjs";

Dependencies are required to be explicitly noted in order to boost the potential for parallelism: Most setup work that will be blocking due to a top-level await (for example, all of the case studies above) can be done in parallel with other setup work from unrelated modules. When some of this work may be highly parallelizable (e.g., network fetches), it's important to get as many of these queued up close to the start of execution as possible.

What is guaranteed about code execution order?

Modules maintain the same ordering as in ES2015 for when they start executing. If a module reaches an await, it will yield control and let other modules initialize themselves in the same well-specified order.

To be specific: Regardless of whether top-level await is used, modules always initially start running in the same post-order traversal established in ES2015: execution of module bodies starts with the deepest imports, in the order that the import statements for them are reached. After a top-level await is reached, control is passed to start the next module in this traversal order, or to other asynchronously scheduled code.

Do these guarantees meet the needs of polyfills?

Currently (in a world without top-level await), polyfills are synchronous. So, the idiom of importing a polyfill (which modifies the global object) and then importing a module which should be affected by the polyfill will still work if top-level await is added. However, if a polyfill includes a top-level await, it will need to be imported by modules that depend on it in order to reliably take effect.

Does the Promise.all happen even if none of the imported modules have a top-level await?

If the module's execution is deterministically synchronous (that is, if it and its dependencies each contain no top-level await), there will be no entry in the Promise.all for that module. In this case, it will run synchronously.

These semantics preserve the current behavior of ES Modules, where, when top-level await is not used, the Evaluate phase is entirely synchronous. The semantics are a bit in contrast with uses of Promises elsewhere. For a concrete example and further discussion, see issue #43 and #47.

How exactly are dependencies waited on? Does it really use Promise.all?

The semantics of modules without top-level await is synchronous: the whole tree executes in postorder, with a module running just after its dependencies have run. The same semantics apply to modules with top-level await: Once the module which contains top-level await has executed, it will trigger the synchronous execution of dependent modules whose dependencies have all executed. If a module does contain top-level await, even if the await is not dynamically reached, the whole module will be treated as "asynchronous", as if it were a big async function. Therefore, anything that runs when it's done is in a Promise reaction. However, from there, if there are multiple modules which are dependent on it, and these do not contain top-level await, then they will run synchronously, without any Promise work between them.

Does top-level await increase the risk of deadlocks?

Top-level await creates a new mechanism for deadlocks, but the champions of this proposal consider the risk to be worth it, because:

  • There are many existing ways that modules can create deadlocks or otherwise halt progress, and developer tools can help in debugging them
  • All deterministic deadlock prevention strategies considered would be overly broad and block appropriate, realistic, useful patterns
Existing Ways to block progress
Infinite Loops
for (const n of primes()) {
  console.log(`${n} is prime}`);
}

Infinite series or lack of base condition means static control structures are vulnerable to infinite looping.

Infinite Recursion
const fibb = n => (n ? fibb(n - 1) : 1);
fibb(Infinity);

Proper tail calls allow for recursion to never overflow the stack. This makes it vulnerable to infinite recursion.

Atomics.wait
Atomics.wait(shared_array_buffer, 0, 0);

Atomics allow blocking forward progress by waiting on an index that never changes.

export function then
// a
export function then(f, r) {}
async function start() {
  const a = await import('a');
  console.log(a);
}

Exporting a then function allows blocking import().

Conclusion: Ensuring continued progress is a larger problem
Rejected deadlock prevention mechanisms

A potential problem space to solve for in designing top level await is to aid in detecting and preventing forms of deadlock that can occur. For example awaiting on a cyclical dynamic import could introduce deadlock into the module graph execution.

The following sections about deadlock prevention will be based on this code example:

// file.html
<script type=module src="a.mjs"></script>

// a.mjs
await import("./b.mjs");

// b.mjs
await import("./a.mjs");
Alternative: Return a partially filled module record

In b.mjs, resolve the Promise immediately, even though a.mjs has not yet completed, to avoid a deadlock.

Alternative: Throw an exception on use of in-progress modules

In b.mjs, reject the Promise when importing a.mjs because that module hasn't completed yet, to prevent a deadlock.

Case study: Race to import() a module

Both of these strategies fall over when considering that multiple pieces of code may want to dynamically import the same module. Such multiple imports would not ordinarily be any sort of race or deadlock to worry about. However, neither of the above mechanisms would handle the situation well: One would reject the Promise, and the other would fail to wait for the imported module to be initialized.

Conclusion: No feasible strategy for deadlock avoidance

Will top-level await work in transpilers?

To the greatest extent possible. The widely deployed CommonJS (CJS) module system does not directly support top-level await, so any transpilation strategy targeting it will need adjustments. However, within this context, we've made several adjustments to the semantics of top-level await based on the feedback and experience of the authors of several JavaScript module systems, including transpiler authors. This proposal aims to be implementable in such contexts.

Without this proposal, module graph execution is synchronous. Does this proposal maintain developer expectations that such loading be synchronous?

To the greatest extent possible. When a module includes a top-level await (even if that await is not dynamically reached), this is not synchronous, and at the very least takes one trip through the Promise job queue. However, module subgraphs which do not use top-level await continue to run synchronously in exactly the same way as without this proposal. And if several modules which do not use top-level await depend on a module which does use it, then those modules will all run when the async module is ready, without yielding to any other work (neither the Promise job queue/microtask queue, nor the host's event loop, etc.). See #74 for details on the logic used.

Should module loading include microtask checkpoints between modules, or yielding to the event loop after modules load?

Maybe! These module loading questions are part of an exciting research area in loading performance, as well as an interesting discussion on the invariants surrounding microtask checkpoints. This proposal doesn't take an opinion on these questions, leaving the asynchronous behavior for separate proposals. Host environments may wrap modules in a way which does these things, and the top-level await specification machinery can be used to coordinate things. A future proposal either in TC39 or in a host environment could add additional microtask checkpoints. For related discussion, see whatwg/html#4400.

Would top-level await work in web pages?

Yes. The details of the integration into the HTML specification is proposed at whatwg/html#4352.

History

The async / await proposal was originally brought to committee in January of 2014. In April of 2014 it was discussed that the keyword await should be reserved in the module goal for the purpose of top-level await. In July of 2015 the async / await proposal advanced to Stage 2. During this meeting it was decided to punt on top-level await to not block the current proposal as top-level await would need to be "designed in concert with the loader".

Since the decision to delay standardizing top-level await it has come up in a handful of committee discussions, primarily to ensure that it would remain possible in the language.

In May 2018, this proposal reached Stage 2 in TC39's process, with many design decisions (in particular, whether to block "sibling" execution) left open to be discussed during Stage 2.

Specification

Implementations

References

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,534
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,498
star
5

proposal-optional-chaining

HTML
4,942
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,252
star
7

proposal-signals

A proposal to add signals to JavaScript.
3,387
star
8

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,321
star
9

proposal-observable

Observables for ECMAScript
JavaScript
3,058
star
10

proposal-decorators

Decorators for ES6 classes
2,640
star
11

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,496
star
12

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
13

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,863
star
14

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,742
star
15

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,722
star
16

proposal-async-await

Async/await for ECMAScript
HTML
1,578
star
17

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,493
star
18

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,429
star
19

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,307
star
20

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,232
star
21

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
22

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
23

proposal-binary-ast

Binary AST proposal for ECMAScript
961
star
24

agendas

TC39 meeting agendas
JavaScript
952
star
25

proposal-built-in-modules

HTML
891
star
26

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
857
star
27

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
746
star
28

proposal-set-methods

Proposal for new Set methods in JS
HTML
655
star
29

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
614
star
30

proposal-operator-overloading

JavaScript
610
star
31

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
591
star
32

proposal-async-context

Async Context for JavaScript
HTML
587
star
33

proposal-bigint

Arbitrary precision integers in JavaScript
HTML
561
star
34

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
540
star
35

ecma402

Status, process, and documents for ECMA 402
HTML
529
star
36

proposal-slice-notation

HTML
523
star
37

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
511
star
38

notes

TC39 meeting notes
JavaScript
496
star
39

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
40

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
HTML
483
star
41

proposal-decimal

Built-in exact decimal numbers for JavaScript
HTML
477
star
42

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
463
star
43

proposal-module-expressions

HTML
433
star
44

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
45

proposal-UnambiguousJavaScriptGrammar

413
star
46

proposal-weakrefs

WeakRefs
HTML
409
star
47

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
48

proposal-error-cause

TC39 proposal for accumulating errors
HTML
380
star
49

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
50

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
374
star
51

proposal-module-declarations

JavaScript Module Declarations
HTML
369
star
52

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
352
star
53

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
54

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
55

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
345
star
56

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
330
star
57

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
319
star
58

tc39.github.io

Get involved in specifying JavaScript
HTML
318
star
59

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
318
star
60

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
61

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
310
star
62

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
63

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
306
star
64

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
65

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
279
star
66

proposal-json-modules

Proposal to import JSON files as modules
HTML
272
star
67

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
270
star
68

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
267
star
69

proposal-promise-with-resolvers

HTML
255
star
70

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
253
star
71

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
242
star
72

proposal-structs

JavaScript Structs: Fixed Layout Objects
230
star
73

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
223
star
74

proposal-intl-relative-time

`Intl.RelativeTimeFormat` specification [draft]
HTML
215
star
75

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
214
star
76

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
214
star
77

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
208
star
78

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
79

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
200
star
80

proposal-optional-chaining-assignment

`a?.b = c` proposal
186
star
81

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
82

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
83

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
178
star
84

proposal-upsert

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert
HTML
176
star
85

proposal-collection-methods

HTML
171
star
86

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
87

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
169
star
88

proposal-extractors

Extractors for ECMAScript
JavaScript
166
star
89

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
166
star
90

proposal-intl-duration-format

164
star
91

how-we-work

Documentation of how TC39 operates and how to participate
161
star
92

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
93

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
94

proposal-extensions

Extensions proposal for ECMAScript
HTML
150
star
95

proposal-hashbang

#! for JS
HTML
148
star
96

proposal-import-meta

import.meta proposal for JavaScript
HTML
146
star
97

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
146
star
98

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
99

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
100

eshost

A uniform wrapper around a multitude of ECMAScript hosts. CLI: https://github.com/bterlson/eshost-cli
JavaScript
142
star