jquery, how to run a function as soon as another function ends

前端 未结 6 1821
梦谈多话
梦谈多话 2021-01-12 18:58

*Note: Re-writing question:

I am trying to write the following outside of the individual function calls:

example:

function f1(){
         


        
6条回答
  •  囚心锁ツ
    2021-01-12 19:24

    I had this problem recently. If you have a bunch of functions that do async stuff, just make them all to return a Deferred, which you manually resolve when the function async job is finished. Then you can put the functions in an array and run them sequentially:

    // Sample asynchronous function that returns Deferred
    var f = function(name){
        console.log('Function root start', name);
        var d = $.Deferred();
        d.done(function(result){
            console.log('Async work finish', name, result);
        });
    
        setTimeout(function(){
            setTimeout(function(){
                d.resolve('Hello');
            }, 200);
        }, 1000);
    
        console.log('Function root finish', name);
        return d;
    };
    
    // Array with functions
    var defs = [];
    defs.push(f.bind(null, 1));
    defs.push(f.bind(null, 2));
    defs.push(f.bind(null, 3));
    
    // Recursive sequential calling
    var i = 0;
    var runAtIndex = function (i) {
        i < defs.length && defs[i]().done(function() { runAtIndex(i + 1); });
    }
    runAtIndex(i);
    

提交回复
热议问题