Learn about when() methods used in jquery.
# Jquery when() Method
when() method in the JQuery helps you to return and process the results of the ajax. This means that you can handle Promise objects that occur when you use ajax. Below is a simple grammar.
$.when(ajax1, ajax2, ...).done(function(resp1, resp2, ...) {
  ...
});

Use multiple ajax with ajax1, ajax2 and process the result with resp1, resp2... in the callback at the back.



! When() is used?
Often used to process results step by step or at the same time on a website that requires multiple ajax calls rather than a single ajax call.

- if different ajax is performed sequentially according to the ajax result.
- If multiple ajax results are required together

The reason why when() is required is because ajax is an asynchronous communication and does not know when all ajax will be processed. For this reason, you can use when() to process Promise objects.



# See when() example
So let's use a simple example to find out. If a shopping mall site uses two api to provide a coupon to a particular user, one is to use your information... What if I have to make sure that the other one is currently subscribed? In this case, we'll only try to write a code that prints the phrase Okay if both results are true. I think there's api in each of them as below

api1 : /userInfo/
api2 : /isValidUser/

Let's now write the function isOkay() below using the when() method to process the results of the above two api simultaneously.
function isOkay() {
  var api1 = "/userInfo/";
  var api2 = "/isValidUser/";
  
  var ajax1 = return $.ajax(api1);
  var ajax2 = return $.ajax(api2);

  $.when(ajax1, ajax2, ...).done(function(resp1, resp2, ...) {
    alert('Okay');
    // 실행할 코드
  });
};

In the example above, the results of ajax1 and ajax2 are simple examples of when() outputting Okay only when resp1 and resp2 are both true.


@ What do you need to know?
The difference between calling ajax one by one is that you should pay close attention to the following:

To receive response results from @ $.when() as resp1, resp2, return the entire function that invokes ajax.
For each response to be processed using when() the following done(), the entire ajax call must be returned. At this point, resp1 returns values in an array, the first value is the ajax result, the second is success, failure, etc. And the third one contains all of the programs and methods associated with the ajax.




# On finishing
Web services that are implemented as micro-services or require multiple ajax calls should use when(). This can also be found at the front-end, such as ajax, real, or vuejs. It is important because it is used very often.