简体   繁体   中英

How to use callback function in Java script functions

I am very new to Java script and need to use callback function in my java script function.I dont know how to use callback function. Below is my code:

function SelectedFeature() {

// Here is my code

call_Method1();

call_Method2();

}

The problem in the above function is that, call_method2() starts executing before call_Method1() ends its execution. To solve this problem, someone told me to use callback function. Now how can i use callback function in my SelectedFeature() function. Please explain by using code sample.

Here is a simple example:

function processData(data) {
    firstStep(data, secondStep);
}    

function firstStep(data, callback) {
    var result = getResult(data);
    if (result.success) {
        callback(result);
    }
}

function secondStep(data) {
    // ...
}

If you are making an ajax call, to stop the execution of call_method2, in ajax request we can do something like,

$.ajax({
  url: "your url",
  type: "Get",
  success: call_Method2,
  failure: call_Method2
});

Now, call_Method2 will run only when call_Method1 is finished.

Here is the solution

 function SelectedFeature() {

    this.call_Method1 = function(data, callback) {
        var success = false; // define success flag with default false

        //your code
        //here write your logic and assign true of false to success based on your code execution
        success = true;

        if (success) {
            //pass data or add one more parametere to call_Method1 if different data
            //this.call_Method1 = function(data,data1,callback){
            //callbackdata1);
            callback(data);
        }
    }

    this.call_Method2 = function(data) {
        console.log(data);
    }

}

var feature = new SelectedFeature();
var data = "some data"
feature.call_Method1(data, feature.call_Method2);

You Can follow this callback structure

function SelectedFeature(call_Method1, call_Method2) {

    // Here is my code

    call_Method1();

    call_Method2();

}

SelectedFeature(function () {
    console.log('call_Method1')
}, function () {
    console.log('call_Method2')
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM