-2

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.

Function1();   
Function2();   

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

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

Thanks...

Isabel Inc
  • 1,871
  • 2
  • 21
  • 28
Harriet
  • 1,633
  • 5
  • 22
  • 36

3 Answers3

1

You can do many ways but a very simple Example

function first(){



// define every thing here and then at the end call your second function



function2();


}

Checkout more possibilities here

Community
  • 1
  • 1
Amar Singh
  • 5,464
  • 2
  • 26
  • 55
0

if your in the browser, just use callback it's the easiest and cross-browser way to do it.

Exemple:

function sayBill() {
   console.log('bill');
}

function sayHiAfterTwoSeconds(callback) {

  setTimeout(function() {
     console.log('hi');

     // call the function you passed in parameter
     if (typeof callback === 'function') {
        callback();
     }
  });

}

sayHiAfterTwoSeconds(sayBill);
// will output 'bill hi'

https://jsfiddle.net/80bbbjco/

If you want better way to do it, but not cross browser there is promise : https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise

Or even more modern but not supported ATM async await: https://jakearchibald.com/2014/es7-async-functions/

Gatsbill
  • 1,760
  • 1
  • 12
  • 25
0

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

Promise:

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

function bar() {
    // do something
};

// Call bar only once foo finishes
foo().then(function() {
   bar();
}, 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';
   cb(data);
}

function bar(name) {
   // some processing
   console.log(name);
}

// 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';
    cb(data);
    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.

Halfpint
  • 3,967
  • 9
  • 50
  • 92
  • Thanks to all who've contributed positively, I will try out some of these suggestions which looks best suited for me. – Harriet Aug 02 '16 at 13:13
  • I decided to go with the callback function proposed by @Gatsbill, but I am sure that other options on this page are good working solutions as well. – Harriet Aug 02 '16 at 14:19
  • I did suggest callbacks too, but sure. Glad you got it working – Halfpint Aug 02 '16 at 14:21
  • i wish i can mark all the answers as the correct one, but I see that I can't. So I will upvote it to be useful instead. Thank you so much for your efforts. – Harriet Aug 02 '16 at 14:25