1

I have a JavaScript bootstrapper module that I'm trying to keep very clean and simnple: Currently I have code like:

function bootStrapper() {
       xmlRepository.getAll().done(function (result) {
       autoPolicyForm.show();       
   });
}

In xmlRepository I am using a deferred object within getAll();

function getAll () {
    var d = $.Deferred();

    $.ajax({
        type: "GET",
        url: "http://localhost/Autopolicy/dataSource.xml",
        dataType: "xml",
        success: function (xml) {
            d.resolve(xml);
        }
    });

    return d.promise();
}

This code is working well but I would really like to simplify the bootstrapper code further to something like:

function bootStrapper() {
       var result = xmlRepository.getAll();
       autoPolicyForm.show();       
   });
}

Everything I try results in 'result' being undefined due to the async nature of call.

Does anyone know how to modify the code to move the complexity to the xmlRepository so that the above can be achieved?

Thanks

4

1 に答える 1

2

In modern jQuery the ajax function returns a promise so you can simplify getAll to :

function getAll () {
    return $.ajax({
        type: "GET",
        url: "http://localhost/Autopolicy/dataSource.xml",
        dataType: "xml"
    });
}

In other words it is now possible to do

$.ajax(url).done(function(xml){...});

You could also change getAll to

   function fetchAll (callback) {
        $.ajax({
            type: "GET",
            url: "http://localhost/Autopolicy/dataSource.xml",
            dataType: "xml"
        }).done(callback);
    }

So you'll do

   xmlRepository.fetchAll(function (result) {
       autoPolicyForm.show(); 
   });

But apart setting async to false, you can't avoid passing a function as the execution is asynchronous. And you should consider that a javascript application is naturally event based so it's fine for the users of an API to use and pass anonymous functions (callbacks).

于 2012-11-28T11:17:31.983 に答える