The transform
What the Babel preset does to async functions, for await loops and generators, and what the runtime does at each step.
Why a transform is necessary
A native await continues the function from the microtask queue of the engine. The engine does not use Promise.prototype.then for this, so a patch of then cannot see it. JavaScript code also cannot see the start of the next step of a native generator. Thus, the library changes each async function and each generator at build time.
The parts of the preset
The preset async-browser-context/babel-preset contains nine Babel plugins, in this order:
- A plugin of this library skips each function with the directive
"async-browser-context runtime". The native async functions of the runtime have this directive, so the other plugins do not change them. - A plugin of this library binds each sync generator to the context of its creation (rule C5). It operates in the
Programvisitor, so it gets the generators before the other plugins change them. - A plugin of this library gives the name of each async function to
coroutine, and of each async generator toasyncGenerator, for the callback hooks. The optionnames: falseremoves this plugin. - A plugin of this library moves each static class field and static block with an async arrow function into a static private method. Thus
thisandsuperof the arrow function stay correct after the async transform. - A plugin of this library gives the async generators to the driver of the runtime. The four async generator helpers of the next plugins come from the runtime:
asyncGeneratorin place ofwrapAsyncGenerator,OverloadYield,awaitAsyncGeneratorandasyncGeneratorDelegate. @babel/plugin-transform-explicit-resource-managementchangesusingandawait usingdeclarations, because a generator cannot containawait using. The preset adds this plugin only with Babel 7.23.9 and later.- A plugin of this library starts the plugin of step 6 on each async generator first. The plugin of step 8 changes the async generators in its own traversal, before step 6 gets their blocks.
@babel/plugin-transform-async-generator-functionschanges the async generators and thefor awaitloops. The preset makes its own traversal also skip the functions with the directive of the runtime.@babel/plugin-transform-async-to-generatorchanges each async function into a generator function. Itsmoduleandmethodoptions make the code usecoroutinefromasync-browser-context/runtime.
Steps 2 to 9 do not change the server code of React Server Components: a file or a function with the directive "use server", "use cache" or "use cache: <kind>". Next.js accepts only native async functions there, and the server keeps the context with the native AsyncLocalStorage. These plugins do not skip the code in the shared traversal of Babel. Thus the other presets, for example @babel/preset-typescript, still change it. The Next.js section of the build tools guide tells more.
The Babel transforms of steps 8 and 9 already handle destructuring, var, labels, closures, sync iterables and the return() use after break. The library adds no custom code for await.
The plugin of step 5 sets the helpers in the Program visitor. Thus the preset also operates with @babel/plugin-transform-runtime, which gives the other helpers of Babel from @babel/runtime.
Show the diagram source
flowchart TB
input["Source module"] --> skip["Plugin of the library: skip the functions of the runtime"]
skip --> bind["Plugin of the library: bind each generator"]
bind --> names["Plugin of the library: name each async function"]
names --> statics["Plugin of the library: move static members with async arrows"]
statics --> helpers["Plugin of the library: async generator helpers from the runtime"]
helpers --> resources["Babel: using and await using"]
resources --> asyncgen["Babel: async generators and for await"]
asyncgen --> asyncfn["Babel: async functions, with coroutine()"]
asyncfn --> output["Module that imports async-browser-context/runtime"]The output
Select an example to compare the input with the output of the real preset. The build of this site makes the output with the preset of the repository.
What coroutine() does
coroutine(generatorFunction) gives an async function. When the code starts that function, coroutine records the current frame. Then it starts the generator, one step at a time:
- Make the frame of the function current.
- Start the next step of the generator. The step operates until the next
yield, which was anawaitbefore the transform. - Record the current frame as the frame of the function. A step can change it with
AsyncLocalStorage.enterWith(). - Make the previous frame current again.
- When the value of the
yieldsettles, go back to step 1.
The coroutine is a native async function, and it awaits the value of each step with a native await. Thus, each await takes the same microtask turns as the await of the source. A native await is also faster than a then callback, mostly in Firefox (browsers).
Before the coroutine awaits an object, it reads the then property of the object in the frame of the function, as a native await does. An error in a parameter default or in a parameter destructuring rejects the promise, as with a native async function.
The first step of the function operates in the step of the caller. Thus an AsyncLocalStorage.enterWith() in the synchronous part of an async function also changes the store of the caller, as on Node.js.
The preset does not change the runtime of the library, because a directive marks its native async functions. Thus, a bundler can apply the preset to all of node_modules. The Vite plugin also skips the files of the runtime by their path.
CautionMinifiers
Terser and other minifiers can remove directives. Do not give the preset a copy of the runtime that a minifier changed. An example is a dependency that bundles and minifies this library. Bundlers minify after the transform of each module, so the usual setups are correct.
What asyncGenerator() does
Babel changes each async generator into a sync generator. Each await becomes yield _awaitAsyncGenerator(value), which gives new OverloadYield(value, 0). Each step of yield* becomes yield new OverloadYield(promise, 1), through the helper asyncGeneratorDelegate. asyncGenerator(generatorFunction) gives a function that makes an async generator object for that generator:
- When the code makes the async generator, record the current frame.
- Queue each
next(),throw()andreturn()of the consumer. Start one request at a time, as a native async generator does. - Start each step of the body in the recorded frame, then make the previous frame current again.
- Continue after each
awaitof the body with a nativeawait. Give each yielded value to the consumer.
The protocol is the protocol of the Babel 8 helper. The runtime also gives the helpers awaitAsyncGenerator and asyncGeneratorDelegate, so the markers are always the OverloadYield class of the runtime. The steps after an await give the name of the async generator to the callback hooks.
What bindGenerator() does
The plugin changes each sync generator function so that it gives bindGenerator(generator). The function keeps its name, its parameters and its kind, so a declaration stays hoisted. The body moves into an inner generator. bindGenerator records the frame of the creation. Each next(), throw() and return() starts its step in that frame, and then makes the frame of the caller current again.
NoteA plain function
After the transform, a generator function is a plain function that gives a generator object. fn.constructor is Function, not GeneratorFunction, and fn.prototype and instanceof fn do not operate as for a native generator function. A library that examines a function to find a generator function, for example co or is-generator-function, sees a plain function. The generator objects operate as native generator objects.
Transform the dependencies
The Vite plugin transforms the dependencies by default. With Babel, configure the loader so that it does not exclude node_modules. Code that the build cannot transform cannot get the context of a different operation. The boundaries page gives the tools that keep the context where your code meets that code.