Malinda Miller
Malinda Miller

Reputation: 191

Javascript callback, execute code after calling a function

I have the following code in my document.ready

  technicianDropdownFromCBU(cbu_id);
  assetsDropdownFromCBU(cbu_id);

  if(#{@appointment.technician_id.present?}){
     $('#appointment_technician_id').val('{@appointment.technician_id}');
}

I only want the if statement to run after the first two functions are finished executing. I can't modify those functions and include the if statement in that code, because the function is called multiple times.

Upvotes: 0

Views: 68

Answers (2)

Yuval Pruss
Yuval Pruss

Reputation: 9826

If you are using jQuery you can use:

function someFunctions(cbu_id) {
    technicianDropdownFromCBU(cbu_id);
    assetsDropdownFromCBU(cbu_id);
}

$.when($.ajax(someFunctions(cbu_id))).then(function () {
    if(#{@appointment.technician_id.present?}){
        $('#appointment_technician_id').val('{@appointment.technician_id}');
    }
});

Upvotes: 1

Maha Dev
Maha Dev

Reputation: 3965

A Simple solution will be, create a callback function and put your if condition in that function. Call your callback function inside the body of your uper functions like this:

function technicianDropdownFromCBU(cbu_id){
   //do you work here
   assetsDropdownFromCBU(cbu_id);
}

function assetsDropdownFromCBU(cbu_id){
   //do you work here
   callback();
}

function callback(){
  if(#{@appointment.technician_id.present?}){
     $('#appointment_technician_id').val('{@appointment.technician_id}');
  }
}

technicianDropdownFromCBU(cbu_id);

Notes: It will execute your functions in sequence. So your if condition will run in the end.

Upvotes: 2

Related Questions