Natural Async Programming
JavaScript has really taken asynchronous programming mainstream, but some of the lessons we've learned along the way is that async is different. Rather than the usual linear program flow, you have these callbacks which can be nested or managed by a control flow lib. However, what if we dreamt something more natural for async programming, because async is awesome and it deserves it.
Promises is the idea that an async function returns an object which handles the outcome of an async action. I like this concept because you're using the return statement where it should be used (output). Inversely, callbacks seem backwards: you use the input to handle the output of a function (how backwards). However, promises are still callbacks, just nicer.
I wondered then, what would it be like if we had async built into a language? How could this work? Could it even work? Let's hypothesize.
Say the return statement was asynchronous in that the function would wait until it is used before it returns output:
function af(){ return setTimeout(function(){ return 'done'; }, 1000) }
Here, setTimeout returns what the callback returns, but it is async so it doesn't return 'done' immediately. This is interesting, but the language would have to know which parts of the code depend on other async operations.
var foo = af(); if (foo === 'done') { alert('second'); } alert('first');
Sense the if-statement depends on foo, then the if statement is put on hold before, and the alert('first') statement is executed.
This will make parallel async and serial async almost invisible to the programmer:
// parallel invocation var a = async(); var b = async(); doSomethingWith(a, b); // Final results // Serial invocation var a = async(); var b = doSomethingWith(a); doSomethingWith(b); // Final results
Some more examples to get used to how this works:
var done = sleep(2000); if (done) { alert('Done sleeping!'); } alert('Sleeping'); var posts = db.query("select * from posts"); var comments = db.query("select * from comments"); // This next statement is using the pending variables // so it will be queued until for later, automatically res.render('template', {posts:posts, comments:comments}); // This will run before the above because it's not depending // on the async pending variables Analytics.push(request);
Somehow, this could be possible with it being implemented at the interpreter level. Could it be done?