How does the $ .when () and the .then () aligned

9

In my studies of javascript with Jquery framework , I have come across several times with $.when() and .then() aligned. I wonder how they work together. an example that I came across was the code below.

$.when(loadView, setData).then(
  function(loadViewResult, setDataResult) {
    // lógica
  }, 
  function(erro) {
    console.log(erro);
  }
});
    
asked by anonymous 25.08.2015 / 01:18

1 answer

8

This code is based on promises ( promises ) implemented in jQuery as < a href="https://api.jquery.com/jQuery.Deferred/"> $.Deferred ). A promise is an object that represents the result of an asynchronous operation (the most common case is an Ajax request), even that it has not yet been completed.

In your code, you have two promises, one called loadView , and another setData . $.when receives both as parameters, and returns another promise that will only be resolved when both are resolved. And the functions passed to then will be executed when that third is resolved - that is, when promises passed to when are all resolved. The first function passed to then executes on success of the two asynchronous operations, and receives the results of them as parameters. The second executes in case of error, that is, if either of the two promises is rejected.

    
25.08.2015 / 02:46