Callback function in user function

There is a way to call a user-defined function after completion. Many jquery include a way to make a callback, for example, when the animation is complete, you can just give it another function as the last parameter. But is there anyway to combine function1(params, function1(){alert('2');}) or something else? I honestly have no idea how that would look.

thanks

+4
source share
5 answers

You can create a function pointer with something like:

 var yourCallback = function() { alert('2'); } 

You can think of it as an object containing the function itself (and not its return value). Since this is an object, you can pass it to other functions.

Then pass this to the function that you are calling as an argument (do not call it with () , as this will pass its return value):

 function1(params, yourCallback); 

Finally, in function1, call your callback when you need it:

 function function1(args, callback) { //Some code if (callback) { callback(); } } 
+5
source

Technically, the template you are asking for is:

 function myFunctionNeedsACallback(param1, callback) { //do stuff with param1 if(typeof callback === "function"){ callback.call(yourThisParam, anyOtherParams); } } 

While this is a useful model ... overuse will result in ugly, uncheckable and unsupported code. Use with discretion.

Your example will work very well:

 myFunctionNeedsACallback(param, function() { alert('2'); }); //will alert 2 after running the rest of the contents of the function 

EDIT

To solve Thomas problem:

 function ajaxCall1(){ return $.ajax(/*your parameters NO SUCCESS CALLBACK NEEDED*/); } function ajaxCall2(){ return $.ajax(/*your parameters NO SUCCESS CALLBACK NEEDED*/); } function ajaxCall3(){ return $.ajax(/*your parameters NO SUCCESS CALLBACK NEEDED*/); } $.when(ajaxCall1(), ajaxCall2(), ajaxCall3()).then(function(results1, results2, results3) { //do stuff with all 3 results without "nesting" things }); 
0
source
 function doSomething(arg1, callback){ // bla bla bla callback(); } 
0
source

You would structure your function like this:

 function one(x, y, z, callback) { // do operations here callback(); } 

Then, since functions are objects that you could pass to functions through a callback parameter, IE:

 one(1, 2, 3, function(){alert('hello');}); 

or

 var func = function() { alert('hello'); }; one(1, 2, 3, func); 

or

 function func() { alert('hello'); } one(1, 2, 3, func); 
0
source

While callbacks are convenient, overuse can lead to ugly and unsupported code. Besides the standard callbacks shown in other answers, you can look at other patterns such as deferred / promises and AOP.

In jQuery, promises are implemented with when () and then () .

requirejs is also a good starting point.

0
source

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


All Articles