MochiKit.Async, synchronousness, and testing

1 view
Skip to first unread message

Kevin Frost

unread,
Mar 14, 2006, 8:35:43 PM3/14/06
to MochiKit
Hi everyone.

A quick search of the group posts strongly implies that I shouldn't
raise the "synchronous" topic yet again, but here I go anyway....

On the one hand, it doesn't seem fair to expect something named Async
to also handle Sync. There are certainly cases where you *have* to
block until the request is handled, but for those getXMLHttpRequest may
be as much Mochi as I should expect to use. And likewise, it doesn't
seem fair to expect Deferred to also know how to be NotDeferred.

On the other hand, this has led me to wonder about testing asynchronous
loads as well as testing synchronous ones. Hopefully someone here will
have the solution at hand, and save me a bunch of work. ;-)

This doesn't work (nor should it necessarily):

function goodEnough(req) {
pass('Request successful'); // well, really I'd use isaOK...
}
function badResponse(err) {
fail('Request failed: ' + err);
}
var d = doSimpleXMLHttpRequest(url);
d.addCallbacks(goodEnough, badResponse);

...because, of course, the test suite has already failed before the
callbacks fire.

So of course I can do something like this, which does work in
principle:

var req = getXMLHttpRequest();
req.open('GET',url,false);
req.send(null);
try {
if (req.status == 200 || req.status == 302) {
pass('Request successful');
}
else {
fail('Request failed: ' + req.status);
}
}
catch(err) {
fail('Request failed: ' + err);
}

...but then the only thing I'm testing is the request itself. I may
want to test that separately anyway, but at some point I need to test
it in conjunction with the callbacks and whatever other goodies I'm
using.

What I think I'd really like is a way to use Async as if it were Sync:
set up my Deferreds ahead of time and tell it to wait for a response;
but otherwise have everything work as it does. Something like this:

var d = new Deferred( goodEnough, badResponse );
doSimpleXMLHttpRequest( url, ( { sync: true, deferred: d } );

That would solve the testing problem and also let me do blocking XML
loads when I need to. I'm inclined to go with this in my own setup,
presumably with a wrapper function.

So, my questions boil down to:

1. Am I missing something?
2. Does anyone else have a better approach to testing Async?
3. Are there philosophical or practical objections to the suggestion?
4. Would it be good to roll this into Async, or better to leave it
separate?

Reply all
Reply to author
Forward
0 new messages