Function chains in jquery so that it starts one by one

I have two functions: functionA () and functionB (), each of which contains $ .getJSON. And, depending on what data is returned by functionA (), function B () will behave differently. I used:

functionA(); functionB(); 

However, with this setting, sometimes I get unexpected results from function B (). My thinking was that the call to the B () JSON function started, although the call to the A () JSON function was not completed. My solution was to put functionB () inside $ .getJSON ".done". And although this works, I was wondering if there is a more elegant way to bind the functions A () and functionB (), so that the function B () does not start until the function A () is completely completed, and at the same time while my call to function B () is outside function A ().

+4
source share
3 answers

I would recommend using callback syntax (well known, for example, from node.js ):

 functionA(functionB); 

So far, your functions accept a callback argument:

 functionA(callback){ // do stuff // when ready, run: return callback(); }; 

If your calls become more complex, you can take a look at the async library

+4
source

There are several ways to achieve this. You obviously need to wait until the function call A () JSON is complete before functionB () is executed. One way to do this is to call function B () from within the success () handler in a call to function A () JSON, for example:

 function functionA() { $.getJSON(url, data, function(result) { // do something functionB(); }); } function functionB() { // do something } functionA(); 

If you do not want to hard code the function function inside function A, you can also pass it as an argument and call it this way, for example:

 function functionA(callback) { $.getJSON(url, data, function(result) { // do something callback(); }); } function functionB() { // do something } functionA(functionB); 

Another, more elegant and scalable solution is to let the function call A () JSON fire a custom event when it is created and create a new event handler for that particular event, which then fires function B. Thus, function A and function B remain completely decoupled, you do not need to know each other, but you can still ensure the correct execution order. You can read about triggering and selecting custom events here: jQuery.trigger

+1
source

$.getJSON is an asynchronous call, so you must call functionB() in your callback for functionA() $ .getJSON if you are not using a synchronous AJAX request.

To use a synchronous request, you need to set the async variable to false using a custom $.ajax request instead of $ .getjson. See jQuery.ajax () docs in ajax options. jQuery.getJSon () docs shows an example of ajax setup for json.

0
source

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


All Articles