Harriet Harriet - 1 year ago 54
jQuery Question

How can one wait for a function to complete before the next function is called?

What is the best way to wait for a function to complete before the next function is called?

I have a scenario where two functions are called consecutively, one after the other. I need the first one to complete before the second one is called.


How do I tell the code to wait for
to complete before attempting

WebDevelopment: solution can be javascript or jQuery, or Ajax based.


Answer Source

You could either use Promise or callback to solve this problem, with Promises being the more modern and cleaner way of doing things:


function foo() {
   return new Promise(function(resolve, reject) {
      // do some work
      // something caused an error whoops

function bar() {
    // do something

// Call bar only once foo finishes
foo().then(function() {
}, function() {
   // this is the reject case an error here

Promises are able to be chained, meaning that if bar was a Promise we could chain another then event to that.

You could also use callbacks to solve your problem

function foo(cb) {
   var data = 'alex';

function bar(name) {
   // some processing

// Call foo, then execute bar when foo finishes
foo(function(data) {
    bar(data);  // alex would be logged once the callback fires

In the callback example here, we pass a function as a parameter, once the running function block encounters your invocation of the cb parameter, it will invoke the function which emulates the asynchronousy. Just remember though that it does not stop the execution context on that function. If we had code like:

function foo(cb) {
    var data = 'alex';
    console.log('this is after so don't print it'); <-- still prints

The final console.log will print when the callback finishes its time on the event queue (unless of course you fire an even in CB like a http request, in which the log will fire and then the http request would finish after).

To stop the last console log you would need to explicitly tell javascript to return when cb is called to prevent further execution in that method, and personally this is where I favour Promises, once you resolve or reject the promise the execution context within that function scope is stopped.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download