How $.when() and . then() aligned works

Asked

Viewed 375 times

9

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

$.when(loadView, setData).then(
  function(loadViewResult, setDataResult) {
    // lógica
  }, 
  function(erro) {
    console.log(erro);
  }
});

1 answer

8


This code is based on promises (Promises, implemented in jQuery as $.Deferred). A promise is an object that represents the result of a asynchronous operation (the most common case is an Ajax request), even if it has not yet been completed.

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

  • 2

    Hey, calm down, you don’t have to accept my answer so fast :) See if something better comes along, I’m running out of time to produce more detailed explanations...

  • 1

    Moderator’s note: I deleted the comments that were up there because they were obsolete after their edition. But I didn’t think any were hostile (I think I know which one you’re talking about). Think about it, it wasn’t comments pointing the finger at you, one was a clarification, and the other was a joke (which was general, I wasn’t making fun of you).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.