In AngularJS 1.3 there is a nice shorthand for $q.defer()
. In fact, it removes the need for calling defer
at all!
[00:00] This is another video about Angular 1.3 and some of the cool things coming in this next version of the Angular. One of the cool things is the $q constructor.
[00:11] Anybody familiar with $q is familiar with this concept of defer and promises. This deferred has two functions that you can invoke resolve and reject, depending on whether some requests exceeded or any number of asynchronous tasks that you want to run.
[00:32] Here, we have a very simple application. We have something that we're doing asynchronously and we're passing in whether to reject the response. Then we set a timeout for 500 milliseconds to make these asynchronous.
[00:48] Then, we just set the done time and whether we decide to reject it or not will determine whether we resolve or reject it. We're basically doing the same thing, resolved that the done time or reject it at the done time.
[01:02] Then, in our application, we have this fire function that we're pass in whether to reject it. We do that asynchronous thing and then, with the data, we'll assign it to the resolved value or rejected the value.
[01:13] That is in our template here with resolved value parses JSON, or rejected value. We'll just give an example of that. Resolve async, reject async. If I resolve again, or reject again, here you can see that updates with the most recent time it was rejected.
[01:31] A very simple app, we're going to go hand and close HTML here, because this is mostly JavaScript that we're going to deal with from here on out.
[01:37] To convert this to the new q constructor format, we no longer are going to be invoking defer on it and instead, we just simply be turning q as a constructor. It sort of be an invocation of q and I'll take a function with resolve and reject.
[01:59] Then, we'll wrap everything inside of our closing curly brace and paren. Then, Instead of deferred, because that no longer exist, we'll simply invoke the resolve that's passed in to this constructor function as well as reject.
[02:15] Here is the converted version. Let's just go ahead and make sure it works. Resolve, async, reject async, and we can invoke it as many times as we so please.
[02:27] If you're familiar with the promise spec, this becomes closer in line to what ES6 is giving us with the promises, with this resolve and reject callback. That's what Angular is trying to do.
[02:41] That's the new q constructor. The old format of doing deferred still works just fine. This is the new format that's kind of future proof with the ES6 style.
Woot woot! :D
OMG and Holy Nightmares Batman! I have wanted this feature for sooo long. And this lesson shows me that the promise constructor is now available in 1.3...