Here’s an example of async code using callbacks:
You might notice the first line of each callback function is checking for errors. This is the only way we can catch errors in this cascading style code. If we don’t check for errors this way and an error occurs — for example, on the call to sendNotificationsToServer — then there’s no way to access the error from outside that specific callback function.
Another issue with this code is it can quickly grow to what’s known as callback hell. We’ve all been there before at least once and, as you might remember, it’s not a happy place to be.
Here’s a new version of the previous code, rewritten using Promises.
Much better, right?
Multiple implementations of the Promises/A+ specification have been available through third-party solutions, like Bluebird, Q, and RSVP. Both AngularJS and Ember.js borrowed from some of these libraries in order to provide their own implementations — Angular’s version is based on the Q library, while Ember uses RSVP.
Since Promises are now part of ES2015, we can expect these frameworks to start moving away from third-party solutions and toward using native Promises as soon as most modern browsers have support for it.
If you’ve recently worked on apps using Ember or Angular2, for example, the syntax for the new module system should look familiar. Here’s an example of what a router file from an Ember application could look like:
The first 2 lines on this file are responsible for importing existing modules: the Ember module (installed via npm) and the module found under the ./config/environment.js file. The last line exports the newly configured Router object, making it available to the module system. All the code in between is completely trapped inside of this module and does not pollute the global namespace.