Keeping Promises with AngularJS
One of the most common methods of accomplishing this is to provide a callback function to the code that’s retrieving information. This is a set of instructions that the web page will act on when it has everything it needs to proceed. It’s a simple process that is used extensively with libraries like jQuery. But it’s not a terribly flexible method of managing this type of work. When using a callback, you are decoupling yourself from that task. You will not have any insight into the status of the task unless it’s explicitly written into the callback function. This gets to be very problematic when you have many interdependent tasks that must be delegated. Without accurate and consistent insight into their status and how they are being handled, you are forced to update code in all sorts of different places to accommodate one workflow. This is what many refer to as “callback hell.”
Here is a simple example that demonstrates how a promise could be used to handle a deferred calculation.
The following example builds upon the previous one and shows how multiple promises can be initialized at the same time. Then, by using the $q.all function, you can wait until the existing promises are fulfilled, and then post a complete message to the screen.