Using generators, TypeScript creates a poor man's async.

submited by
Style Pass
2021-05-16 06:20:06

This post is part of an ongoing series on TypeScript. In it, I try to explain in a detailed way different situations I’ve faced while building relatively big React applications using TypeScript, and moving them from JavaScript. Here’s a list of other posts I’ve written about TypeScript:

Other articles on the web explain this idea[1] [2]. This is my take on it using TypeScript. I find it interesting because it lets me explore how generator functions are typed. Also, some libraries have implemented their versions of this before async await existed. The two I could find are bluebird’s coroutine and co.

Instead of async and await, the stars of the show are going to be our own function asynq and a JavaScript keyword yield, specific to generator functions. If generator functions and iterators are new concepts to you, I suggest you read some documentation[3] [4] first.

This loop calls iterable.next() with no arguments automatically for us. This is not what we want! We want to pass our own values to next. We need fine-grained control over what we pass to each next call, and a for..of loop would be making that decision for us by passing undefined to next until the generator is done.

Leave a Comment