-2

I use jquery 1.8.2
I have these functions(below), but i want to call the bar() funtion when foo() have finished which dosen't happen. How can i do this?

function foo() {
  //something time consuming
  console.log("foo")
}
function bar() {
  console.log("bar");
}
function helloWorld() {
  foo();
  bar();
}
Flipsanta
  • 62
  • 1
  • 9

3 Answers3

4

You have several ways to do this. Right now, I can think of two I regularly use. The first one (and easiest to understand) is to use callbacks. Simply pass to the first function the second you want to call, as an argument.

function foo(callback) {
    setTimeout(function(){
        console.log("foo");
        callback();
    }, 500);
}

function bar() {
    console.log("bar");
}

function helloWorld() {
    foo(bar)
}

helloWorld();

(JSFiddle)

This doesn't require any extra libraries, but when you have a lot of asynchronous stuff, the code quickly becomes a mess.

The other solution, a bit harder to understand but much more powerful, is to use Promises.

Promises are a great way to deal with asynchronous code by offering proper methods to deal with it. The only downside is that you need to learn them, and use an external library.

EDIT: As pointed out, I didn't use the JQuery API. Here is how it would looks like using it:

function foo() {
    var deferred = jQuery.Deferred();
    setTimeout(function(){
        console.log("foo");
        deferred.resolve();
    }, 500);
    return deferred.promise();
}

function bar() {
    console.log("bar");
}

function helloWorld() {
  foo().then(bar);
}

helloWorld();

(JSFiddle)

Following example is based on Q.

function foo() {
    var deferred = Q.defer();
    setTimeout(function(){
        console.log("foo");
        deferred.resolve();
    }, 500);
    return deferred.promise;
}

function bar() {
    console.log("bar");
}

function helloWorld() {
    foo().then(bar);
}

helloWorld();

(JSFiddle)

nioKi
  • 1,259
  • 9
  • 17
0

function method1(){ // some code

}

function method2(){
   // some code
}

$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})
Megha Nagpal
  • 170
  • 4
0

As simple as below:

DEMO

function foo() {
  var deferred=$.Deferred(); //create a deferred object
  console.log("foo");
  return deferred.resolve() //once logging done resolve it and send back
}
function bar() {
  console.log("bar");
}
function helloWorld() {
  $.when(foo()).done(bar()); //you can use $.when and done
}
$(document).ready(function(){
  helloWorld();  
})
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200