Skip to content

Instantly share code, notes, and snippets.

@theefer
Last active September 11, 2016 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theefer/a0e1d75a27473251b42998a3653cbb65 to your computer and use it in GitHub Desktop.
Save theefer/a0e1d75a27473251b42998a3653cbb65 to your computer and use it in GitHub Desktop.
Why multiple top-level await quickly become fiddlier than one might think

Properly concurrent top-level await

Besides the valid concerns @Rich_Harris has raised, another thing to worry about is the way await makes it very easy to cause asynchronous work to be scheduled sequentially when it could be parallelised (and hence faster).

Consider the following:

import {getDayOfWeek} from './static-dep';

const dish = getDayOfWeek() === 'friday' ? 'fish' : 'chicken';
const meal = await import(`./dynamic-dep-${dish}`);

const inBrowser = typeof window !== undefined;
const ajax = await import(inBrowser ? './dynamic-dep-browser' : './dynamic-dep-node');

// ...

While it looks nice, it's also inefficient, because the second dynamic dependency won't be requested until the first one is returned, even though they do not depend on each other.

The correct way to write the same code with concurrent loading is:

import {getDayOfWeek} from './static-dep';

const dish = getDayOfWeek() === 'friday' ? 'fish' : 'chicken';
const inBrowser = typeof window !== undefined;

const [meal, ajax] = await Promise.all([
  import(`./dynamic-dep-${dish}`),
  import(inBrowser ? './dynamic-dep-browser' : './dynamic-dep-node')
]);

// ...

Not quite as nice, is it?

How many people will write the latter version instead of the former?

Note that this is a risk with using await in any code, not just top-level, but the impact of unnecessarily sequencing dependency loading in particularly worrying.

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