The function returned by $Y (the wrapping function) meets the following requirements:
It always returns an instance of jsx3.$AsyncRV.
It can take any of a number of parameters. Consult the API documentation of the function for the expected parameters.
A Simple Example
Any function passed to the when() method of jsx3.$AsyncRV is called when the asynchronous method is done.
The function is passed a single parameter, which is the asynchronous return value of the asynchronous function, as in the following example:
var rv = loadXmlAsync("data.xml");
rv.when(function(doc) {
jsx3.log("The asynchronous return value is: " + doc);
});
Multiple Callbacks
A program can call when() any number of times before or after the asynchronous method finishes. Regardless of when it is called, all callbacks are invoked. For example:
Use the and() and or() methods of jsx3.$AsyncRV to chain asynchronous return conditions. Both methods also return instances of jsx3.$AsyncRV. For example:
var rv1 = loadXmlAsync("data1.xml");
var rv2 = loadXmlAsync("data2.xml");
rv1.and(rv2).when(function() {
jsx3.log("Got docs: " + rv1.rv() +
" and " + rv2.rv());
});
Automatic Parameter Resolution
If an instance of jsx3.$AsyncRV is passed as a parameter to an asynchronous function, the function automatically waits for the parameter to be available before calling the wrapped function.
This can eliminate a call to when() and an anonymous function, thereby improving code readability and conciseness.
var getURL = jsx3.$Y(function(cb) {
cb.done("data.xml");
});
var asyncURL = getURL();
loadXmlAsync(asyncURL).when(function(doc) {
jsx3.log("Got document: " + doc +
" from URL " + asyncURL.rv());
});
The previous code is equivalent to but more concise than the following code.
var getURL = jsx3.$Y(function(cb) {
cb.done("data.xml");
});
var asyncURL = getURL();
asyncURL.when(function(url) {
loadXmlAsync(url).when(function(doc) {
jsx3.log("Got document: " + doc +
" from URL " + url);
});
});