0

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);
1
  • How would you solve the same problem if the functions were synchronous and not using promises? Commented Aug 16, 2020 at 19:15

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that is what I was looking for. Order will always be the same. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.