function return string javascript code example

function return string javascript

1

1 Example

0
var states = {};//cache of state names, with state abbreviations as keys
function getState(abbr) {
    var dfrd = $.Deferred();//A deferred object, whose promise will be returned.
    if(!states[abbr]) {
        $.ajax({
            url: "states.asp",
            dataType: 'XML',
            success: function(data) {
                //Load up the cache
                $.each($('state', data), function(i, el) {
                    states[el.attr('abbr')] = $(el).text();
                });
                //Now resolve or reject the deferred object depending in whether states[abbr] has been cached
                if(states[abbr]) {
                    dfrd.resolve(abbr, states[abbr]);//Success! Let's resolve the deferred object (and its promise).
                }
                else {
                    dfrd.reject(abbr, 'States successfully downloaded but ' + abbr + ' was not included');
                }
            },
            error: function() {
                dfrd.reject(abbr, 'Download of states failed');
            }
        });
    }
    else {
        //The state name is already cached
        //The deferred object (and its promise) can be resolved without needing to make another ajax call.
        dfrd.resolve(abbr, states[abbr]);
    }
    return dfrd.promise();
}

Other Code Examples