How to add callback to .apply () method?

In my code, I have an array of function calls. I iterate over these calls and use .apply () to call them. The problem is that if calling a new function takes some time, the loop will be .apply () and will call the next function before the previous function is finished. > & L .; Here is an example:

function someFunc(element, calls){ if(calls.length){ fn = calls[0]; calls.shift(); fn.apply(element, args); someFunc(element, calls); } } 

So, if there was a callback to the apply function, this could work the way I want it. i.e.

 function someFunc(element, calls){ if(calls.length){ fn = calls[0]; calls.shift(); fn.apply(element, args, function(){ someFunc(element, calls); }); } } 

I also have a question about calling someFunc inside the callback function. The functions in my calls array affect my element variable. So I want to make sure that after it changes, it will be passed to someFunc in the callback so that the next function can also manipulate it. Sometimes they just confuse me with this context. :)

If this helps, I use jQuery. I know how to add callbacks to jQuery methods, but I donโ€™t know how to do this when I deal with my own JavaScript code. How to add a .apply () method callback?

+6
source share
1 answer

Make sure that every function you call returns a promise . You can then โ€œwaitโ€ for this promise to be โ€œresolvedโ€ before continuing with the following function on your list:

 function someFunc(element, calls) { if (calls.length) { var fn = calls.shift(); fn.apply(element, args).done(function(el) { // what args? el = el || element; // default to previous element if necessary someFunc(el, calls); }); } } 

each function looks something like this:

 function myFunc1(el) { var def = $.Deferred(); // do something async, and "resolve" the deferred object in the async callback ...(function() { def.resolve(el); // this "el" will get passed to the next function }); return def.promise(); } 

If the asynchronous task is an AJAX call, you can simply return the jqXHR result from $.ajax directly, rather than creating a new deferred object.

+2
source

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


All Articles