oneday
oneday

Reputation: 1629

Callback function doesn't exectute

So, I have two functions and I would like the second one to execute only after the first one has finished.

This is the case:

$('.link').on('click', function(e){
  e.preventDefault();

  function myLoopOne () {      
    console.log('first function executed');
  }

  function myLoop () {          
    console.log('second function executed');
  }

  myLoopOne(function(){
    myLoop();
  });

});

Unfortunately, only the first function executes and the callback function myLoop() doesn't get called.

Could anyone please tell me what I'm doing wrong?

Upvotes: 1

Views: 55

Answers (2)

vijay
vijay

Reputation: 926

Try this, Need to add callback as a parameter and method call inside the function which call another function. Not only a callback , you can pass any word as a parameter and method call.

$('.link').on('click', function(e) {
  e.preventDefault();
  myLoopOne(myLoop);
});

// need to add callback as a parameter and method call inside the function which call another function
function myLoopOne(callback) {
  console.log('first function executed');
  callback();
}

function myLoop() {
  console.log('second function executed');

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="link">Click me</button>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to use the reference of the function you provide to myLoopOne() and call it, like this:

$('.link').on('click', function(e) {
  e.preventDefault();

  function myLoopOne(callback) { // < receive the function reference
    console.log('first function executed');
    callback && callback(); // < call the referenced function, if one was provided
  }

  function myLoop() {
    console.log('second function executed');
  }

  myLoopOne(function() {
    myLoop();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="link">Click me</button>

Note that this pattern only applies to asynchronous code. It's redundant if you're working synchronously.

Upvotes: 3

Related Questions