Unblocking sleep semantics

Jussi Kalliokoski jussi.kalliokoski at gmail.com
Tue Jan 17 11:56:44 PST 2012


Hey everyone!

I'm new here, although I often read the mailing list, so, hi!

Anyway, I've been thinking about unblocking sleep semantics for ES, meaning
that you could write functions that you do asynchronous things, while
preserving the code flow. An example could be the require() function,
familiar from node.js, used like this:

require('foo.js').foo();

However, when you go to the browser world, the modules usually have to be
loaded asynchronously, if similar semantics is used, meaning that you would
have to use AMD or similar patterns. Also, anything that loads 3 or more
files in node.js before doing something is going to be spaghetti without
some of the various frameworks designed for that, and even then it isn't
pretty. Writing a CLI build tool in node.js is a nightmare.

The remedy I'm suggesting is unblocking sleep semantics. Many people
complain that ES doesn't even have sleep(), etc and non-blocking isn't the
answer for everything. However in the event-driven model of ES as it's
mostly used, things like sleep() don't make much sense, since asynchronous
nature is the very power of ES. What we need is actually mainly sugar,
making your code look prettier, make it easier to follow. And so I came up
with this suggestion (for which I have two possible syntaxes for, verbose
and less verbose, but more on that later):

Example: sleep()

function sleep (time) {
  var ready = return function;
  setTimeout(ready, time);
}

sleep(5000)
// Do something

So, the core idea of my suggestion is to block the stack and save it for
later (until the ready is called), but block nothing but the active stack!
Meaning any event listener or else could fire while the sleep is going on.
This would bring some funny way of concurrency to JS as well. As you can
see here, the semantics is fully backwards compatible (this would be a
syntax error in ES5, no additional reserved words or operators). The return
function markup would return a function that follows the normal async
callback pattern ( callback(err, value); ), and when it's called, it will
either return a value or throw respectively at the callstack where the
active function has been called.

I have a slightly more complex semantics for this as well, but I personally
prefer this one as it's more lightweight and even further backwards
compatible.

For a more complex example and the more verbose semantics, see:
https://gist.github.com/7c5e476e056800f94493

So, let me know what you think, and if I was unclear about something.

Cheers,
Jussi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120117/a7f89b21/attachment-0001.html>


More information about the es-discuss mailing list