Book Image

PhoneGap for Enterprise

By : Kerri Shotts
Book Image

PhoneGap for Enterprise

By: Kerri Shotts

Overview of this book

Table of Contents (16 chapters)
PhoneGap for Enterprise
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 one for a success callback...