gfxmonk

gfxmonk

1p

1 comments posted · 0 followers · following 0

14 years ago @ Eli Grey - Pausing JavaScript wit... · 1 reply · +1 points

Interesting stuff, as I've recently been set onto the path of NarrativeJS and Strands in order to save the same sort of problems. They seemed wonderful at first, but I encountered a handful of bugs with both, and debugging was a nightmare.

Having said that, I must admit that it took me a good day or so to actually wrap my head around what's actually going on here. I'm still not sure if I'm doing things oddly, but I thought I'd share the function call descriptor generator that I find most natural:

Function.prototype.result = function() {
var self=this;
var wrapper = function(func_args, cb) {
func_args = Array.prototype.slice.call(func_args);
func_args = func_args.slice();
func_args.push(cb);
async(self).apply(this, func_args);
}
return [wrapper, arguments];
}

this allows me to just have all my functions be regular (non-async-aware) functions that expect one more argument than they're called with (the callback argument). Sample usage:

function add_one(arg, cb) {
cb(arg + 1);
}

function main() {
alert("1 + 1 = " + (yield add_one.result(1)));
}

async(main)();

The to function-call-description generator does feel less awkward to write with, but it seems to require functions be available in the global scope, which wouldn't work for me. And this way, I don't have to write wrapper functions for everything that just uses a callback without being async-aware. it also wrapps everything in as async() call as it goes, so that it should correctly deal with a yield wherever in the stack it occurs.