Skip to content

Delimited Generators - Minimal Delimited Control for JS

License

Notifications You must be signed in to change notification settings

manuel/delimgen

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Delimited Generators - Minimal Delimited Control for JS

Overview

This library implements delimited control operators as a very thin (50 LOC) layer over plain ES6 generators.

It doesn’t add any expressive power over plain generators, but I think it offers a more intuitive API. Specifically, tasks like waiting for a promise to settle, spawning a new independent generator, or implementing a blocking event loop become straightforward.

With a small constant overhead (having to use function*, using yield* for every blocking call, and using next() to kickstart generators from an ordinary, non-generator function), one can write asynchronous JS programs in a quasi-direct style.

Check out the introductory blog post.

Examples

A single generator that runs in an infinite loop. Each time through the loop it prints something and then sleeps. Demonstrates the core API.

Demonstrates spawning multiple generators with their own independent loops.

Demonstrates a blocking main event loop, and multiple independent generators.

API

run(generator)

Spawns a new generator that can use suspend and resume.

suspend(suspension_handler)

Suspends the currently running generator, and calls the suspension handler in the place where the generator was originally run. The suspension handler receives the suspended generator as its single argument.

resume(generator, resumption_handler)

Resumes a suspended generator, and calls the resumption handler without arguments in the place where the generator was previously suspended.

Notes

In terms of delimited control, this library implements single-prompt continuations that can only be resumed once (this is a fundamental limitation of generators, but personally I haven’t needed multiply-resumable continuations yet).

Multiple prompts could be added quite easily I think, but I haven’t really needed those either, yet.

The API functions run, suspend, and resume roughly correspond to push_prompt, take_subcont, and push_delim_subcont, respectively, from Oleg’s caml-shift library.

About

Delimited Generators - Minimal Delimited Control for JS

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published