How to use callback function in JavaScript functions

I am very new to JavaScript and I need to use the callback function in my java script function. I do not know how to use the callback function. Below is my code:

function SelectedFeature() { // Here is my code call_Method1(); call_Method2(); } 

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

I am making an asynchronous request in call_Method1() . I need call_method2() be called after completion of call_Method1() . But in my case, calls to call_method2() before call_Method1() complete its execution. Now how can I fix this?

+4
source share
3 answers

What do you use for an asynchronous call? Did you encode it yourself or use the jQuery library?

You can simply impose a bool to say β€œwork” that you set to true when method 1 starts and returns to false when it ends. you could wait for method2 until the work is true.

0
source

You need to reorganize call_method1() to accept and execute the callback after it completes:

 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, therefore, referring to them by their name, you can transfer them, like any other value.

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

+7
source

The question has already been confirmed by Felix. Inspired by his answer and the problem that I am experiencing in the current project, I wrote a small entity in which there is a class that adds a bit of extra security.

To summarize, you pass the callback function in the same way you pass a variable. Then the receiver activates it as a function.

 myCoolFunction: function( data ) { // Do some thing with response } $.get( '/some/cool/url', myCoolFunction ); 

In the above $.get callback is myCoolFunction with the data parameter after receiving the data

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

To be careful, I have a CoffeeScript class (and its JavaScript compilation) that will perform some security checks.

It does nothing magic, checks to see if its function is and returns if it does not return an empty function to reduce the chance of a JS error. https://gist.github.com/ziyan-junaideen/8717925

0
source

Source: https://habr.com/ru/post/1343523/


All Articles