Search code examples
jquerypromisedeferred

jquery promise function chaining


I am trying to create a sequence of functions that are chained together. The following does what I want, but I want to be able to call any of the functions alone to start the sequence. For example, if I called one() it would run one(), then two(), then three(), then complete(). If I called three() it would run three then complete(). Is there a way to 'link' each function to the one below it without calling it like one().then(two).then(three).then(complete); but instead just one(), or just two(), etc?

function one() {
    var d = $.Deferred();
    
    console.log('one');
    setTimeout(function() {
        d.resolve();
    }, 5000);
    
    return d.promise();
}

function two() {
    var d = $.Deferred();
    
    console.log('two');
    setTimeout(function() {
        d.resolve();
    }, 5000);
    
    return d.promise();
}

function three() {
    var d = $.Deferred();
    
    console.log('three');
    setTimeout(function() {
        d.resolve();
    }, 5000);
    
    return d.promise();
}

function complete() {
    
    console.log('done');
}

one().then(two).then(three).then(complete);

Solution

  • Assuming order is always the same just add a then() inside each one and call the next in sequence there.

    function one() {
        var d = $.Deferred();        
        console.log('one');
        setTimeout(d.resolve, 1000);       
        return d.promise().then(two);
    }
    
    function two() {
        var d = $.Deferred();    
        console.log('two');
        setTimeout(d.resolve, 1000);    
        return d.promise().then(three);
    }
    
    function three() {
        var d = $.Deferred();    
        console.log('three');
        setTimeout(d.resolve, 1000);    
        return d.promise().then(complete);
    }
    
    function complete() {    
        console.log('done');
    }
    
    one();
    setTimeout(()=>{console.log('Start at three'); three()}, 5000)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>