maxtaco/tamejs — Issue #23: Mixing Sync and Async functions
Author: debonet
Created: 2011-11-12 06:07:10+00:00
State: open

I'm new to TameJS, so I might not know the preferred way to do this. But I'm having difficulty combining synchronous and asynchronous function calls.

Here's what I'd like to be able to do:

await{
async(function(){console.log("A");defer();});
async(function(){console.log("B");defer();});
}
console.log("DONE");

Where async is some asynchronous function, such as:

function async(fxn){
setTimeout(fxn,Math.random()*3000);
}

I'd like to get the output A,B,DONE (or B,A,DONE). But it does not work as expected. Instead I get DONE,A,B (or DONE,B,A).

A second attempt:

await{
var def=defer();
var def2=defer();
async(function(){console.log("A");def();});
async(function(){console.log("B");def2();});
}
console.log("DONE");

fails with the error: "ReferenceError: defer is not defined"

However, if I add parens around the defer() calls, it works as desired. e.g.:

await{
var def=(defer());
var def2=(defer());
async(function(){console.log("A");def();});
async(function(){console.log("B");def2();});
}
console.log("DONE");

It seems the second/parens issue is a problem with the parser. Perhaps its only expecting defer()'s to be used directly within function arguments.

However, it also seems that the first code could be supportable as well, if the parser could look within subfunctions. Of course, you then have a namespace issue, where you'd need to figure out which await{} a defer() belongs to. I *think* it is always unambiguous, since it seems await{} and defer() always happen in the same lexical scope.

But, perhaps there are some screwball cases where defer() happens elsewhere? if so perhaps await{} could take a name, e.g.:

await foo {
async(function(){
await{
async(function(){console.log("HERE"); defer());
foo.defer();
}
});
}

(though the above example is unambiguous even without the foo label).