forcing one javascript function to wait to run until the first has finished

孤街醉人 提交于 2019-12-20 06:34:16

问题


Afternoon all, I am running into an issue where i need to run one function, then after that is finished, run the next, and do this for four functions, i have been at this for a while trying to find the correct syntax to layout my function calls in and cant seem to find anything to address this specific scenario.

html:

<div id = "putcontenthereafterajax">
</div><!--end putcontenthereafterajax-->

<div id = "putfooterhereafterajax">
</div<!--end putfooterhereafterajax-->

jquery:

$(window).load(function() { 


function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        //alert("I cached "+this+"");
    });
    $('#progressbarinner').css("width","200px");//change the width of the inner progress bar div
}

function changecss(){
    $('.hidetillcache').css("visibility","visible");//make the page visible
    $('#loadingscreen').fadeOut("slow");
}

function contentajax(){
    $.post("templates/content.php",
    {
        whatamidoing:"imgettingthecontent"
    },
    function(data){
        $('#putcontenthereafterajax').after(''+data+'');
        $('#progressbarinner').css("width","400px");//change the width of the inner progress bar div
    });
}

function footerajax(){
    $.post("templates/footer.php",
    {
        whatamidoing:"imgettingthefooter"
    },
    function(data){
        $('#putfooterhereafterajax').after(''+data+'');
        $('#progressbarinner').css("width","500px");//change the width of the inner progress bar div
    }); 
}

preload([
    'images/careers.jpg',
    'images/careers.png',
    'images/contact.jpg',
    'images/facebook.png',
    'images/footer.png',
    'images/footerblack.png',
    'images/footergrey.png',
    'images/home.jpg',
    'images/media.jpg',
    'images/media.png',
    'images/myitv3.jpg',
    'images/newindex.jpg',
    'images/newindex.png',
    'images/services.jpg',
    'images/twitter.png'
], contentajax(), footerajax(), csschanges());

});

basically i have a loading bar that fills up a bit after each function is finished which in turn requries each function to be ran one after another in the correct order, all the functions do work, the caching and the ajax and even the css changes work. however i cant seem to find a way to force them in the right order and to wait to run until the previous is finished in order to compliment the loading bar. Anyone have any ideas?


回答1:


You want to chain asynchronous function calls.

Use jQuery's deffered.then method :

ajax functions, like $.ajax(), $.post(), $.get(), return a Deferred object.

You can use this in your case :

function contentajax(){
    // add the return instruction to return the Deferred object
    return $.post("templates/content.php", {... });
}

function footerajax(){
    //same here
    return $.post("templates/footer.php", { ... }); 
}

// chain the deferred calls :
contentajax()
   .then( footerajax() )
   .then( csschanges() )

If you also want to wait for the loading of the images to complete, you can still use this Deferred abstraction by wrapping the loading mechanism inside a single Promise. I googled around and found this gist (due credit should be given to the author : Adam Luikart).




回答2:


Try to use callback function.

  • Instead of using .css try using .animation({'':''},200,function(){"........another function here......"})
  • Same with fadeOut as .fadeOut(200,function(){".....another function here........."})

So at the end you will only call contentajax().

Hope that helps.




回答3:


By default your ajax calls are async. You can't guarantee the order of returns async. It sounds like you want execution in synchronous order. Either use async: false in your ajax calls, or use each next function as a success callback to the current one and don't loop through them in preload.

        success: function(data, textStatus, jqXHR)
        {
                successCallback(successCallbackArgs);
        }


来源:https://stackoverflow.com/questions/16302301/forcing-one-javascript-function-to-wait-to-run-until-the-first-has-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!