简体   繁体   中英

How to use callback function in JavaScript functions

I am very new to JavaScript and need to use callback function in my java script function. I don't know how to use a 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 a callback function. Now how can I use callback function in my SelectedFeature() function? Please explain by using code sample.

I'm making an asynchronous request in call_method1() . I need call_Method2() should be called after completing execution call_method1() . But in my case, call_method2() calls before call_method1() completes its execution. Now how can I fix this?

You have to refactor call_method1() to accept and execute a callback after it finished execution:

call_method1(call_method2);

and

function call_method1(callback) {
    // ...
    // do asynchronous stuff, when the response is processed, call
    if(typeof callback === 'function') {
        callback();
    }
    // ...
}

Functions are first class citizens, so by referring to them by their name, you can pass them around like any other value.

We could help better if you post the code for call_method1 .

The question has already been answered above by Felix. Inspired by his answer and an issue I am having in a current project, I wrote a little gist that has a class that adds up a little extra safety.

To sum up, you pass a callback function just as the way you pass a variable. Then the receiver will trigger it as a function.

myCoolFunction: function( data ) {
  // Do some thing with response
}

$.get( '/some/cool/url', myCoolFunction );

In the above $.get calls back myCoolFunction with the parameter data once the data is fetched

What happens if myCoolFunciton is a variable. Well it depends on how the receiver handles the input.

Just to be careful, I have a CoffeeScript class ( and its JavaScript compilation ) that will do some safety checks.

It doesn't do any thing magic, checks if its a function and returns, if not returns an empty function so that it would reduce possibility of JS error. https://gist.github.com/ziyan-junaideen/8717925

What are you using to do your asynchronous call? Did you code it yourself or are you using a library like JQuery?

You could simply put a bool to say "working" that you set to true as method 1 starts and back to false when it finishes. you could then have method2 wait while working is true.

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