JQuery was quite successful in explaining promises with $q object. They came up with deferred object which did a great job in making things easier. Theory was all good but i never got a confidence of completely utilizing promises until couple of months back. In my last Angular project, I finally got into trouble of a good async callbacks hell.
Before I explain the exact promise situation, let me tell you something about my trip to LA before I tackled this problem. It was a super hectic 3 day trip.
- We planned to fly early morning on Day 1 and cover Disney on day 1 itself.
- Day 2 depends completely on our situation which we return in from Disney.
- If we are super exhausted, then we will go and relax on Venice beach.
- If not, we will go to Universal. Hollywood, Getty, Fame would all depend on how much time is remaining after we finish the previous two spots. So every day was dependent on previous days outcome.
I am assuming that you probably have figured out by now that it wasn’t an emotional or thrilling travel story. Yup, you got it, it’s a background to Promises.
Lets talk technical now.
You make a call to a function which calls an API. Promise is Unfulfilled.
API either Fulfills or Rejects the Promise and returns the response.
The calls to different APIs are asynchronous but Promises make this operation work like a transaction.
Depending upon what’s returned, it goes to the original function’s either
The key to promises is the concept of unfulfilled, fulfilled or rejected. Once you create a sequence of these promises, you have a clear flow of inputs and outputs, and clear code for others to read. You can use the 3 different states to track the progress of the entire chain of promises. The style is synchronous (sequential), even though the actual execution is asynchronous.
It gets even trickier if instead of a single promise, the eventual output depends on multiple promises. So one function, calls two promises, which internally call promises for each API call and all this should be marked as resolved only when each of the promises are resolved. Fortunately, my situation WAS like that otherwise I would have never tried this complex loop of promises.
$q.all: The $q.all() method combines multiple promises into a single promise that is resolved when all of the input promises are resolved or one of them to reject() and then executes the provided callback function.
Thanks for reading. ❤️ it if this article could clarify some of the confusing concepts of Promises.