Try.these :: Utility Methods

Try.these(Function...) -> firstOKResult Accepts an arbitrary number of functions and returns the result of the first one that doesn't throw an error.

This method provides a simple idiom for trying out blocks of code in sequence. Such a sequence of attempts usually represents a downgrading approach to obtaining a given feature.

In this example from Prototype's Ajax library, we want to get an XMLHttpRequest object. Internet Explorer 6 and earlier, however, does not provide it as a vanilla JavaScript object, and will throw an error if we attempt a simple instantiation. Also, over time, its proprietary way evolved, changing COM interface names.

Try.these will try several ways in sequence, from the best (and, theoretically, most widespread) one to the oldest and rarest way, returning the result of the first successful function.

If none of the blocks succeeded, Try.these will return undefined, which will cause the getTransport method in the example below to return false, provided as a fallback result value.

getTransport: function() {

return Try.these(

function() { return new XMLHttpRequest() },

function() { return new ActiveXObject('Msxml2.XMLHTTP') },

function() { return new ActiveXObject('Microsoft.XMLHTTP') }

) || false;

}

Prototype API 1.5.0 - prototypejs.org