Promises
Before we go any further, it's important that you understand the concept of Promises. You can find the specification for Promises at http://promisesaplus.com if you want to read it, but in short, Promises allow us to avoid callback hell when working with asynchronous operations. Because every request we make to a Cordova plugin or to our backend via XHR (XMLHttpRequest
) is asynchronous and requires callbacks, it would be very easy to descend into an unmaintainable mess of spaghetti code.
The callback pattern looks like the following:
doSomethingAsync ( function ( results ) { // do something with results });
While this isn't terribly hard to understand when we're only using one level of callback, it can quickly escalate, as in the following:
step1 ( function ( results ) { step2 ( function ( results ) { step3 ( function ( results ) { step4 ( function ( results ) { … }) }) }) })
Should the methods require multiple callbacks (perhaps...