Call a function after previous function is complete












152















I have the following JavaScript code:



$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});


How can I ensure that function2 is called only after function1 has completed?










share|improve this question




















  • 22





    is function1 performing an async operation?

    – LiraNuna
    Feb 15 '11 at 6:10






  • 7





    Yads, if function1 contains animations, function2 will be executed while function1's animations are still happening. How would you make function2 wait until everything started in function1 is completely done?

    – trusktr
    Mar 5 '11 at 21:45











  • Can someone explain to me why there needs to be anything done to ensure function2 is not invoked until function1 is complete? There is no asynchronous operation happening here so function2 will not run until function1 is complete anyways as this operation is synchronous.

    – Aaron
    Jun 20 '16 at 13:54











  • Possible duplicate of How do I return the response from an asynchronous call?

    – Liam
    Feb 15 '18 at 16:47
















152















I have the following JavaScript code:



$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});


How can I ensure that function2 is called only after function1 has completed?










share|improve this question




















  • 22





    is function1 performing an async operation?

    – LiraNuna
    Feb 15 '11 at 6:10






  • 7





    Yads, if function1 contains animations, function2 will be executed while function1's animations are still happening. How would you make function2 wait until everything started in function1 is completely done?

    – trusktr
    Mar 5 '11 at 21:45











  • Can someone explain to me why there needs to be anything done to ensure function2 is not invoked until function1 is complete? There is no asynchronous operation happening here so function2 will not run until function1 is complete anyways as this operation is synchronous.

    – Aaron
    Jun 20 '16 at 13:54











  • Possible duplicate of How do I return the response from an asynchronous call?

    – Liam
    Feb 15 '18 at 16:47














152












152








152


51






I have the following JavaScript code:



$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});


How can I ensure that function2 is called only after function1 has completed?










share|improve this question
















I have the following JavaScript code:



$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});


How can I ensure that function2 is called only after function1 has completed?







javascript jquery






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 25 '17 at 16:04









Tot Zam

3,85443253




3,85443253










asked Feb 15 '11 at 6:07









RrryyyaaannnRrryyyaaannn

99251112




99251112








  • 22





    is function1 performing an async operation?

    – LiraNuna
    Feb 15 '11 at 6:10






  • 7





    Yads, if function1 contains animations, function2 will be executed while function1's animations are still happening. How would you make function2 wait until everything started in function1 is completely done?

    – trusktr
    Mar 5 '11 at 21:45











  • Can someone explain to me why there needs to be anything done to ensure function2 is not invoked until function1 is complete? There is no asynchronous operation happening here so function2 will not run until function1 is complete anyways as this operation is synchronous.

    – Aaron
    Jun 20 '16 at 13:54











  • Possible duplicate of How do I return the response from an asynchronous call?

    – Liam
    Feb 15 '18 at 16:47














  • 22





    is function1 performing an async operation?

    – LiraNuna
    Feb 15 '11 at 6:10






  • 7





    Yads, if function1 contains animations, function2 will be executed while function1's animations are still happening. How would you make function2 wait until everything started in function1 is completely done?

    – trusktr
    Mar 5 '11 at 21:45











  • Can someone explain to me why there needs to be anything done to ensure function2 is not invoked until function1 is complete? There is no asynchronous operation happening here so function2 will not run until function1 is complete anyways as this operation is synchronous.

    – Aaron
    Jun 20 '16 at 13:54











  • Possible duplicate of How do I return the response from an asynchronous call?

    – Liam
    Feb 15 '18 at 16:47








22




22





is function1 performing an async operation?

– LiraNuna
Feb 15 '11 at 6:10





is function1 performing an async operation?

– LiraNuna
Feb 15 '11 at 6:10




7




7





Yads, if function1 contains animations, function2 will be executed while function1's animations are still happening. How would you make function2 wait until everything started in function1 is completely done?

– trusktr
Mar 5 '11 at 21:45





Yads, if function1 contains animations, function2 will be executed while function1's animations are still happening. How would you make function2 wait until everything started in function1 is completely done?

– trusktr
Mar 5 '11 at 21:45













Can someone explain to me why there needs to be anything done to ensure function2 is not invoked until function1 is complete? There is no asynchronous operation happening here so function2 will not run until function1 is complete anyways as this operation is synchronous.

– Aaron
Jun 20 '16 at 13:54





Can someone explain to me why there needs to be anything done to ensure function2 is not invoked until function1 is complete? There is no asynchronous operation happening here so function2 will not run until function1 is complete anyways as this operation is synchronous.

– Aaron
Jun 20 '16 at 13:54













Possible duplicate of How do I return the response from an asynchronous call?

– Liam
Feb 15 '18 at 16:47





Possible duplicate of How do I return the response from an asynchronous call?

– Liam
Feb 15 '18 at 16:47












8 Answers
8






active

oldest

votes


















175














Specify an anonymous callback, and make function1 accept it:



$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});


function function1(param, callback) {
...do stuff
callback();
}





share|improve this answer





















  • 10





    +1 but if he's using 1.5 he can just use the new Deferreds pattern

    – philwinkle
    Feb 15 '11 at 6:15






  • 2





    Glad to help spread the jQuery lovin'

    – philwinkle
    Feb 15 '11 at 6:27






  • 13





    This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

    – trusktr
    Mar 19 '11 at 8:20






  • 3





    @trusktr Wish I could -1 your comment. Answer is perfectly valid.

    – GoodSp33d
    Jun 30 '13 at 7:43






  • 11





    @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

    – trusktr
    Jul 2 '13 at 3:25



















85














If you're using jQuery 1.5 you can use the new Deferreds pattern:



$('a.button').click(function(){
if(condition == 'true'){
$.when(function1()).then(function2());
}
else {
doThis(someVariable);
}
});


Edit: Updated blog link:



Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/






share|improve this answer





















  • 2





    But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

    – user113716
    Feb 15 '11 at 6:22








  • 9





    That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

    – trusktr
    Mar 19 '11 at 8:17








  • 1





    Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

    – Spencer Williams
    Mar 13 '14 at 16:45






  • 1





    Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

    – Teepeemm
    Apr 10 '14 at 14:30






  • 1





    Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

    – philwinkle
    Apr 16 '14 at 14:15



















33














This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.



Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:



$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable).then(function() {
//this function is executed after function1
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});


function function1(param, callback) {
return new Promise(function (fulfill, reject){
//do stuff
fulfill(result); //if the action succeeded
reject(error); //if the action did not succeed
});
}


This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:



function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});


You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):



Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});


As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:



$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});





share|improve this answer


























  • Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

    – charlietfl
    May 22 '18 at 2:10











  • @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

    – Domysee
    May 22 '18 at 20:51













  • Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

    – charlietfl
    May 22 '18 at 20:58





















31














Try this :



function method1(){
// some code

}

function method2(){
// some code
}

$.ajax({
url:method1(),
success:function(){
method2();
}
})





share|improve this answer
























  • excellent solution. worked for me

    – Adeel Shekhani
    Jul 21 '18 at 15:40






  • 1





    Brilliant hack :)

    – Muntashir Akon
    Jul 26 '18 at 9:16



















19














Or you can trigger a custom event when one function completes, then bind it to the document:



function a() {
// first function code here
$(document).trigger('function_a_complete');
}

function b() {
// second function code here
}

$(document).bind('function_a_complete', b);


Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.






share|improve this answer
























  • "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

    – CodeVirtuoso
    Dec 19 '13 at 9:41



















2














This depends on what function1 is doing.



If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.



If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:



function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}

function MyCallback(result)
{
function2(result);
}





share|improve this answer































    0














    I had a problem with this. Despite using the above code, it wasn't working. Later with others help I realized that my first function was asynchronous and second function was synchronous.



    Hence the asynchronous one was getting executed after the synchronous function despite the code I wrote.



    I found a workaround in my case by calling the second function at the end of my first function.






    share|improve this answer































      0














      If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :



      function function1 (someVariable) {
      var date = Date.now ();
      while (Date.now () - date < 2000); // function1 takes some time to complete
      console.log (someVariable);
      }
      function function2 (someVariable) {
      console.log (someVariable);
      }
      function onClick () {
      window.setTimeout (() => { function1 ("This is function1"); }, 0);
      window.setTimeout (() => { function2 ("This is function2"); }, 0);
      console.log ("Click handled"); // To show that the function will return before both functions are executed
      }
      onClick ();


      The output will be :



      Click handled


      ...and after 2 seconds :



      This is function 1
      This is function 2


      This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.



      Notice that this as funny as it may the code difficult to understand...






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5000415%2fcall-a-function-after-previous-function-is-complete%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        8 Answers
        8






        active

        oldest

        votes








        8 Answers
        8






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        175














        Specify an anonymous callback, and make function1 accept it:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable, function() {
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        ...do stuff
        callback();
        }





        share|improve this answer





















        • 10





          +1 but if he's using 1.5 he can just use the new Deferreds pattern

          – philwinkle
          Feb 15 '11 at 6:15






        • 2





          Glad to help spread the jQuery lovin'

          – philwinkle
          Feb 15 '11 at 6:27






        • 13





          This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:20






        • 3





          @trusktr Wish I could -1 your comment. Answer is perfectly valid.

          – GoodSp33d
          Jun 30 '13 at 7:43






        • 11





          @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

          – trusktr
          Jul 2 '13 at 3:25
















        175














        Specify an anonymous callback, and make function1 accept it:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable, function() {
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        ...do stuff
        callback();
        }





        share|improve this answer





















        • 10





          +1 but if he's using 1.5 he can just use the new Deferreds pattern

          – philwinkle
          Feb 15 '11 at 6:15






        • 2





          Glad to help spread the jQuery lovin'

          – philwinkle
          Feb 15 '11 at 6:27






        • 13





          This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:20






        • 3





          @trusktr Wish I could -1 your comment. Answer is perfectly valid.

          – GoodSp33d
          Jun 30 '13 at 7:43






        • 11





          @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

          – trusktr
          Jul 2 '13 at 3:25














        175












        175








        175







        Specify an anonymous callback, and make function1 accept it:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable, function() {
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        ...do stuff
        callback();
        }





        share|improve this answer















        Specify an anonymous callback, and make function1 accept it:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable, function() {
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        ...do stuff
        callback();
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Feb 15 '11 at 6:20

























        answered Feb 15 '11 at 6:11









        Mike RobinsonMike Robinson

        19.6k85279




        19.6k85279








        • 10





          +1 but if he's using 1.5 he can just use the new Deferreds pattern

          – philwinkle
          Feb 15 '11 at 6:15






        • 2





          Glad to help spread the jQuery lovin'

          – philwinkle
          Feb 15 '11 at 6:27






        • 13





          This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:20






        • 3





          @trusktr Wish I could -1 your comment. Answer is perfectly valid.

          – GoodSp33d
          Jun 30 '13 at 7:43






        • 11





          @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

          – trusktr
          Jul 2 '13 at 3:25














        • 10





          +1 but if he's using 1.5 he can just use the new Deferreds pattern

          – philwinkle
          Feb 15 '11 at 6:15






        • 2





          Glad to help spread the jQuery lovin'

          – philwinkle
          Feb 15 '11 at 6:27






        • 13





          This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:20






        • 3





          @trusktr Wish I could -1 your comment. Answer is perfectly valid.

          – GoodSp33d
          Jun 30 '13 at 7:43






        • 11





          @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

          – trusktr
          Jul 2 '13 at 3:25








        10




        10





        +1 but if he's using 1.5 he can just use the new Deferreds pattern

        – philwinkle
        Feb 15 '11 at 6:15





        +1 but if he's using 1.5 he can just use the new Deferreds pattern

        – philwinkle
        Feb 15 '11 at 6:15




        2




        2





        Glad to help spread the jQuery lovin'

        – philwinkle
        Feb 15 '11 at 6:27





        Glad to help spread the jQuery lovin'

        – philwinkle
        Feb 15 '11 at 6:27




        13




        13





        This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

        – trusktr
        Mar 19 '11 at 8:20





        This answer isn't the solution. Here's proof it doesn't work: jsfiddle.net/trusktr/M2h6e

        – trusktr
        Mar 19 '11 at 8:20




        3




        3





        @trusktr Wish I could -1 your comment. Answer is perfectly valid.

        – GoodSp33d
        Jun 30 '13 at 7:43





        @trusktr Wish I could -1 your comment. Answer is perfectly valid.

        – GoodSp33d
        Jun 30 '13 at 7:43




        11




        11





        @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

        – trusktr
        Jul 2 '13 at 3:25





        @MikeRobinson Here's the problem: What if the ...do stuff contains things that are asynchronous? Function2 will still not fire when expected. The example in my comment above shows that because the foo() function has asynchronous code in it, bar() does not fire it's content after foo()'s content is done executing, even using $.when().then() to call them one after the other. This answer is only valid if (and only if) all the stuff at ...do stuff in your code is strictly synchronous.

        – trusktr
        Jul 2 '13 at 3:25













        85














        If you're using jQuery 1.5 you can use the new Deferreds pattern:



        $('a.button').click(function(){
        if(condition == 'true'){
        $.when(function1()).then(function2());
        }
        else {
        doThis(someVariable);
        }
        });


        Edit: Updated blog link:



        Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/






        share|improve this answer





















        • 2





          But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

          – user113716
          Feb 15 '11 at 6:22








        • 9





          That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:17








        • 1





          Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

          – Spencer Williams
          Mar 13 '14 at 16:45






        • 1





          Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

          – Teepeemm
          Apr 10 '14 at 14:30






        • 1





          Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

          – philwinkle
          Apr 16 '14 at 14:15
















        85














        If you're using jQuery 1.5 you can use the new Deferreds pattern:



        $('a.button').click(function(){
        if(condition == 'true'){
        $.when(function1()).then(function2());
        }
        else {
        doThis(someVariable);
        }
        });


        Edit: Updated blog link:



        Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/






        share|improve this answer





















        • 2





          But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

          – user113716
          Feb 15 '11 at 6:22








        • 9





          That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:17








        • 1





          Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

          – Spencer Williams
          Mar 13 '14 at 16:45






        • 1





          Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

          – Teepeemm
          Apr 10 '14 at 14:30






        • 1





          Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

          – philwinkle
          Apr 16 '14 at 14:15














        85












        85








        85







        If you're using jQuery 1.5 you can use the new Deferreds pattern:



        $('a.button').click(function(){
        if(condition == 'true'){
        $.when(function1()).then(function2());
        }
        else {
        doThis(someVariable);
        }
        });


        Edit: Updated blog link:



        Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/






        share|improve this answer















        If you're using jQuery 1.5 you can use the new Deferreds pattern:



        $('a.button').click(function(){
        if(condition == 'true'){
        $.when(function1()).then(function2());
        }
        else {
        doThis(someVariable);
        }
        });


        Edit: Updated blog link:



        Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 30 '13 at 15:36

























        answered Feb 15 '11 at 6:15









        philwinklephilwinkle

        6,28412043




        6,28412043








        • 2





          But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

          – user113716
          Feb 15 '11 at 6:22








        • 9





          That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:17








        • 1





          Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

          – Spencer Williams
          Mar 13 '14 at 16:45






        • 1





          Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

          – Teepeemm
          Apr 10 '14 at 14:30






        • 1





          Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

          – philwinkle
          Apr 16 '14 at 14:15














        • 2





          But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

          – user113716
          Feb 15 '11 at 6:22








        • 9





          That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

          – trusktr
          Mar 19 '11 at 8:17








        • 1





          Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

          – Spencer Williams
          Mar 13 '14 at 16:45






        • 1





          Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

          – Teepeemm
          Apr 10 '14 at 14:30






        • 1





          Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

          – philwinkle
          Apr 16 '14 at 14:15








        2




        2





        But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

        – user113716
        Feb 15 '11 at 6:22







        But is that a working example? What is being deferred? You're executing function1 and function2 immediately. (I'm not the original commenter.)

        – user113716
        Feb 15 '11 at 6:22






        9




        9





        That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

        – trusktr
        Mar 19 '11 at 8:17







        That's not working at all for me. function1 and function2 both get executed at exactly the same time (as observable by the human eye). Here's the tiny example: jsfiddle.net/trusktr/M2h6e

        – trusktr
        Mar 19 '11 at 8:17






        1




        1





        Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

        – Spencer Williams
        Mar 13 '14 at 16:45





        Rebecca Murphy's write up was before Defferds were introduced to jQuery and it uses examples based on how the writer thinks it will be implemented. Please visit jQuery's site to see how to actually use this feature: api.jquery.com/jQuery.Deferred

        – Spencer Williams
        Mar 13 '14 at 16:45




        1




        1





        Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

        – Teepeemm
        Apr 10 '14 at 14:30





        Even with jQuery 1.5 or something modern, don't you want $.when(function1).then(function2); (without the parentheses that call the function)?

        – Teepeemm
        Apr 10 '14 at 14:30




        1




        1





        Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

        – philwinkle
        Apr 16 '14 at 14:15





        Reading these comments a few years late. function1 should return a promise. In that case it needs to be the actual executed function, not the reference. When resolve is called on that promise then function2 is executed. This is easily explained by assuming that function1 has an ajax call. The done callback would then resolve the promise. I hope that's clear.

        – philwinkle
        Apr 16 '14 at 14:15











        33














        This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.



        Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable).then(function() {
        //this function is executed after function1
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
        });
        }


        This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:



        function1(someVariable).then(function() {
        function2(someOtherVariable);
        }).then(function() {
        function3();
        });


        You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):



        Promise.resolve($.ajax(...params...)).then(function(result) {
        //whatever you want to do after the request
        });


        As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:



        $.ajax(...params...).then(function(result) {
        //whatever you want to do after the request
        });





        share|improve this answer


























        • Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

          – charlietfl
          May 22 '18 at 2:10











        • @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

          – Domysee
          May 22 '18 at 20:51













        • Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

          – charlietfl
          May 22 '18 at 20:58


















        33














        This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.



        Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable).then(function() {
        //this function is executed after function1
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
        });
        }


        This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:



        function1(someVariable).then(function() {
        function2(someOtherVariable);
        }).then(function() {
        function3();
        });


        You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):



        Promise.resolve($.ajax(...params...)).then(function(result) {
        //whatever you want to do after the request
        });


        As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:



        $.ajax(...params...).then(function(result) {
        //whatever you want to do after the request
        });





        share|improve this answer


























        • Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

          – charlietfl
          May 22 '18 at 2:10











        • @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

          – Domysee
          May 22 '18 at 20:51













        • Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

          – charlietfl
          May 22 '18 at 20:58
















        33












        33








        33







        This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.



        Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable).then(function() {
        //this function is executed after function1
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
        });
        }


        This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:



        function1(someVariable).then(function() {
        function2(someOtherVariable);
        }).then(function() {
        function3();
        });


        You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):



        Promise.resolve($.ajax(...params...)).then(function(result) {
        //whatever you want to do after the request
        });


        As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:



        $.ajax(...params...).then(function(result) {
        //whatever you want to do after the request
        });





        share|improve this answer















        This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.



        Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:



        $('a.button').click(function(){
        if (condition == 'true'){
        function1(someVariable).then(function() {
        //this function is executed after function1
        function2(someOtherVariable);
        });
        }
        else {
        doThis(someVariable);
        }
        });


        function function1(param, callback) {
        return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
        });
        }


        This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:



        function1(someVariable).then(function() {
        function2(someOtherVariable);
        }).then(function() {
        function3();
        });


        You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):



        Promise.resolve($.ajax(...params...)).then(function(result) {
        //whatever you want to do after the request
        });


        As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:



        $.ajax(...params...).then(function(result) {
        //whatever you want to do after the request
        });






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 22 '18 at 20:54

























        answered Sep 22 '15 at 13:26









        DomyseeDomysee

        9,24384265




        9,24384265













        • Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

          – charlietfl
          May 22 '18 at 2:10











        • @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

          – Domysee
          May 22 '18 at 20:51













        • Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

          – charlietfl
          May 22 '18 at 20:58





















        • Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

          – charlietfl
          May 22 '18 at 2:10











        • @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

          – Domysee
          May 22 '18 at 20:51













        • Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

          – charlietfl
          May 22 '18 at 20:58



















        Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

        – charlietfl
        May 22 '18 at 2:10





        Promise.resolve wrapping $.ajax is anti-pattern since $.ajax returns thennable promise

        – charlietfl
        May 22 '18 at 2:10













        @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

        – Domysee
        May 22 '18 at 20:51







        @charlietfl but it is not an actual Promise, it just implements the interface. I'm not sure how it behaves when passing a real Promise to its then method, or what a Promise.all would do if a jqXHR and a Promise are passed to it. For that I need to do further testing. But thank you for the hint, I will add it to the answer!

        – Domysee
        May 22 '18 at 20:51















        Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

        – charlietfl
        May 22 '18 at 20:58







        Actually in jQuery version 3+ is Promises A+ compliant. Irregardless $.ajax.then is not new

        – charlietfl
        May 22 '18 at 20:58













        31














        Try this :



        function method1(){
        // some code

        }

        function method2(){
        // some code
        }

        $.ajax({
        url:method1(),
        success:function(){
        method2();
        }
        })





        share|improve this answer
























        • excellent solution. worked for me

          – Adeel Shekhani
          Jul 21 '18 at 15:40






        • 1





          Brilliant hack :)

          – Muntashir Akon
          Jul 26 '18 at 9:16
















        31














        Try this :



        function method1(){
        // some code

        }

        function method2(){
        // some code
        }

        $.ajax({
        url:method1(),
        success:function(){
        method2();
        }
        })





        share|improve this answer
























        • excellent solution. worked for me

          – Adeel Shekhani
          Jul 21 '18 at 15:40






        • 1





          Brilliant hack :)

          – Muntashir Akon
          Jul 26 '18 at 9:16














        31












        31








        31







        Try this :



        function method1(){
        // some code

        }

        function method2(){
        // some code
        }

        $.ajax({
        url:method1(),
        success:function(){
        method2();
        }
        })





        share|improve this answer













        Try this :



        function method1(){
        // some code

        }

        function method2(){
        // some code
        }

        $.ajax({
        url:method1(),
        success:function(){
        method2();
        }
        })






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 18 '14 at 7:31









        TuanTruongTuanTruong

        31132




        31132













        • excellent solution. worked for me

          – Adeel Shekhani
          Jul 21 '18 at 15:40






        • 1





          Brilliant hack :)

          – Muntashir Akon
          Jul 26 '18 at 9:16



















        • excellent solution. worked for me

          – Adeel Shekhani
          Jul 21 '18 at 15:40






        • 1





          Brilliant hack :)

          – Muntashir Akon
          Jul 26 '18 at 9:16

















        excellent solution. worked for me

        – Adeel Shekhani
        Jul 21 '18 at 15:40





        excellent solution. worked for me

        – Adeel Shekhani
        Jul 21 '18 at 15:40




        1




        1





        Brilliant hack :)

        – Muntashir Akon
        Jul 26 '18 at 9:16





        Brilliant hack :)

        – Muntashir Akon
        Jul 26 '18 at 9:16











        19














        Or you can trigger a custom event when one function completes, then bind it to the document:



        function a() {
        // first function code here
        $(document).trigger('function_a_complete');
        }

        function b() {
        // second function code here
        }

        $(document).bind('function_a_complete', b);


        Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.






        share|improve this answer
























        • "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

          – CodeVirtuoso
          Dec 19 '13 at 9:41
















        19














        Or you can trigger a custom event when one function completes, then bind it to the document:



        function a() {
        // first function code here
        $(document).trigger('function_a_complete');
        }

        function b() {
        // second function code here
        }

        $(document).bind('function_a_complete', b);


        Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.






        share|improve this answer
























        • "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

          – CodeVirtuoso
          Dec 19 '13 at 9:41














        19












        19








        19







        Or you can trigger a custom event when one function completes, then bind it to the document:



        function a() {
        // first function code here
        $(document).trigger('function_a_complete');
        }

        function b() {
        // second function code here
        }

        $(document).bind('function_a_complete', b);


        Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.






        share|improve this answer













        Or you can trigger a custom event when one function completes, then bind it to the document:



        function a() {
        // first function code here
        $(document).trigger('function_a_complete');
        }

        function b() {
        // second function code here
        }

        $(document).bind('function_a_complete', b);


        Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 28 '12 at 19:16









        de Raadde Raad

        959919




        959919













        • "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

          – CodeVirtuoso
          Dec 19 '13 at 9:41



















        • "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

          – CodeVirtuoso
          Dec 19 '13 at 9:41

















        "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

        – CodeVirtuoso
        Dec 19 '13 at 9:41





        "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document." api.jquery.com/bind

        – CodeVirtuoso
        Dec 19 '13 at 9:41











        2














        This depends on what function1 is doing.



        If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.



        If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:



        function1()
        {
        new AjaxCall(ajaxOptions, MyCallback);
        }

        function MyCallback(result)
        {
        function2(result);
        }





        share|improve this answer




























          2














          This depends on what function1 is doing.



          If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.



          If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:



          function1()
          {
          new AjaxCall(ajaxOptions, MyCallback);
          }

          function MyCallback(result)
          {
          function2(result);
          }





          share|improve this answer


























            2












            2








            2







            This depends on what function1 is doing.



            If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.



            If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:



            function1()
            {
            new AjaxCall(ajaxOptions, MyCallback);
            }

            function MyCallback(result)
            {
            function2(result);
            }





            share|improve this answer













            This depends on what function1 is doing.



            If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.



            If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:



            function1()
            {
            new AjaxCall(ajaxOptions, MyCallback);
            }

            function MyCallback(result)
            {
            function2(result);
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 15 '11 at 6:13









            RussellRussell

            10.3k1868119




            10.3k1868119























                0














                I had a problem with this. Despite using the above code, it wasn't working. Later with others help I realized that my first function was asynchronous and second function was synchronous.



                Hence the asynchronous one was getting executed after the synchronous function despite the code I wrote.



                I found a workaround in my case by calling the second function at the end of my first function.






                share|improve this answer




























                  0














                  I had a problem with this. Despite using the above code, it wasn't working. Later with others help I realized that my first function was asynchronous and second function was synchronous.



                  Hence the asynchronous one was getting executed after the synchronous function despite the code I wrote.



                  I found a workaround in my case by calling the second function at the end of my first function.






                  share|improve this answer


























                    0












                    0








                    0







                    I had a problem with this. Despite using the above code, it wasn't working. Later with others help I realized that my first function was asynchronous and second function was synchronous.



                    Hence the asynchronous one was getting executed after the synchronous function despite the code I wrote.



                    I found a workaround in my case by calling the second function at the end of my first function.






                    share|improve this answer













                    I had a problem with this. Despite using the above code, it wasn't working. Later with others help I realized that my first function was asynchronous and second function was synchronous.



                    Hence the asynchronous one was getting executed after the synchronous function despite the code I wrote.



                    I found a workaround in my case by calling the second function at the end of my first function.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Feb 7 '18 at 7:42









                    Rahul MakhijaRahul Makhija

                    314




                    314























                        0














                        If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :



                        function function1 (someVariable) {
                        var date = Date.now ();
                        while (Date.now () - date < 2000); // function1 takes some time to complete
                        console.log (someVariable);
                        }
                        function function2 (someVariable) {
                        console.log (someVariable);
                        }
                        function onClick () {
                        window.setTimeout (() => { function1 ("This is function1"); }, 0);
                        window.setTimeout (() => { function2 ("This is function2"); }, 0);
                        console.log ("Click handled"); // To show that the function will return before both functions are executed
                        }
                        onClick ();


                        The output will be :



                        Click handled


                        ...and after 2 seconds :



                        This is function 1
                        This is function 2


                        This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.



                        Notice that this as funny as it may the code difficult to understand...






                        share|improve this answer






























                          0














                          If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :



                          function function1 (someVariable) {
                          var date = Date.now ();
                          while (Date.now () - date < 2000); // function1 takes some time to complete
                          console.log (someVariable);
                          }
                          function function2 (someVariable) {
                          console.log (someVariable);
                          }
                          function onClick () {
                          window.setTimeout (() => { function1 ("This is function1"); }, 0);
                          window.setTimeout (() => { function2 ("This is function2"); }, 0);
                          console.log ("Click handled"); // To show that the function will return before both functions are executed
                          }
                          onClick ();


                          The output will be :



                          Click handled


                          ...and after 2 seconds :



                          This is function 1
                          This is function 2


                          This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.



                          Notice that this as funny as it may the code difficult to understand...






                          share|improve this answer




























                            0












                            0








                            0







                            If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :



                            function function1 (someVariable) {
                            var date = Date.now ();
                            while (Date.now () - date < 2000); // function1 takes some time to complete
                            console.log (someVariable);
                            }
                            function function2 (someVariable) {
                            console.log (someVariable);
                            }
                            function onClick () {
                            window.setTimeout (() => { function1 ("This is function1"); }, 0);
                            window.setTimeout (() => { function2 ("This is function2"); }, 0);
                            console.log ("Click handled"); // To show that the function will return before both functions are executed
                            }
                            onClick ();


                            The output will be :



                            Click handled


                            ...and after 2 seconds :



                            This is function 1
                            This is function 2


                            This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.



                            Notice that this as funny as it may the code difficult to understand...






                            share|improve this answer















                            If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :



                            function function1 (someVariable) {
                            var date = Date.now ();
                            while (Date.now () - date < 2000); // function1 takes some time to complete
                            console.log (someVariable);
                            }
                            function function2 (someVariable) {
                            console.log (someVariable);
                            }
                            function onClick () {
                            window.setTimeout (() => { function1 ("This is function1"); }, 0);
                            window.setTimeout (() => { function2 ("This is function2"); }, 0);
                            console.log ("Click handled"); // To show that the function will return before both functions are executed
                            }
                            onClick ();


                            The output will be :



                            Click handled


                            ...and after 2 seconds :



                            This is function 1
                            This is function 2


                            This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.



                            Notice that this as funny as it may the code difficult to understand...







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jan 1 at 12:16

























                            answered Dec 28 '18 at 15:29









                            StashOfCodeStashOfCode

                            464




                            464






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5000415%2fcall-a-function-after-previous-function-is-complete%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas