简体   繁体   中英

how to use callback on multiple functions in ajax reponse

I have a problem with my javascript code loader hides but it should hide on the last of the jax response.

function reverseGeocoding(lat,lng, callback){
    var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
    $.ajax({
        url: url,                       
        crossDomain:true,
        success: function(response){
               fn1(response,mapobject);   //takes 30 seconds
               fn2(response,mapobject);   //takes 10 seconds
               fn3(response,mapobject);   //takes 30 seconds
               fn4(response,mapobject);   //takes 20 seconds
               fn5(response,mapobject);   //takes 30 seconds
               fn6(response,mapobject);   //takes 30 seconds
               fn7(response,mapobject);   //takes 40 seconds
               $("#loader").show();

        }
    });

}

but the problem is that loader show after response comes. i want to show loader after all function call fn1,fn2,fn3,fn4,fn5,fn6,fn7. please help

You can use $.Deffered , particulalry $.when and $.then . Assuming in all of your functions you are performing an $.ajax request, they should look like this:

function f1() {
    return $.ajax({
        url: "someUrl",
        success: function (data) {
            console.log("f1 done")
        }
    });
}

Such function will return a promise , whicn can be then placed inside your callback using $.when :

 $.when(f1(), f2(), f3()).then(function () {
     console.log("all done!");
 });

Fiddle sample

you can use jquery deferred object.

http://api.jquery.com/deferred.done/

var dfd = $.Deferred();

    dfd
        .done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
        .done(function( n ) {
            $( "p" ).append( n + " we're done." );
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM