async are closely related.
Yield and Async
We quickly recall how
async work on some examples.
yield allows to write generators. The generators are special functions which can pause their execution on a
yield and resume on a
.next(). We can also compose generators with
async helps to write asynchronous operations in a synchronous-like manner. For example we can sequence API calls using the
The main monadic operator is
bind and executes two computations in sequence. The promises are a well-used form of monad. The sequencing operator of the promises is
Now you know what a monad is!
The continuation of an expression is a function representing which computations remain to be done to terminate the current function (or program). For example in:
the continuation of
await firstApiCall(param) to terminate the function
foo is the code represented in green:
which expressed as a function becomes:
Putting everything together
Let us draw a parallel between the
async notations as follows:
We sequence generators with the keyword
yield* and promises with
await. Using our previous definitions, we can say that:
yield*is a syntactic sugar to apply the monadic sequencing operator of the generators to the current continuation;
awaitis a syntactic sugar to apply the monadic sequencing operator of the promises to the current continuation.
If we take back our
we can desugar the first
await into a
.then applied to the continuation:
If we desugar the second
await we get:
which is what we would write without the
The power of the
await use the current continuation at compilation time, as we can view them as syntactic sugars 1. In constrast, the
yield operator gives access to the continuation at run time. We apply the current continuation returned by
yield with the
In particular, we can implement the
async notation at run time with the
yield, by doing a
.then with the current continuation returned by the
.next. This is exactly what some libraries like
co do. By applying the same technique, we can actually implement an
async-like notation for most monads thanks to the
yield operator 2. For the fun of it, we give a full example in this JSBin for the state monad.
async simplify the definition of impure functions. The key operators are
await which sequences two computations. More precisely, these operators apply the monadic sequencing combinator
bind to the current continuation of an expression.
async create promises, but the generators are more generic. Indeed, at runtime, a generator can be interpreted to any side effect thanks to the
yield operator which returns the current continuation.