Vik Denic
vik’s code journal
2 min readJan 28, 2016

--

How Promises Replaced My Pyramid Code

As a mobile developer, most of the code I’ve written has been in Swift / Objective-C and Java. However, to build a truly dynamic app, you will likely need to learn other languages to get the job done. In fact, many of my iOS apps contain nearly as much JavaScript on the server-side as there is Swift (or Obj-C) on the front-end.

Often is the case when using Cloud Code in conjunction with Parse. I am able to respond to the creation and updating of objects on the server-side. This allows for the implementation of dynamic processes that would be otherwise impossible through code running locally on a device.

But when working with numerous, nested callbacks in JavaScript, things can get messy quick. You will end up with what is called Pyramid code, which can be difficult to read and maintain.

I had definitely written some pyramid code in my latest project, where I need multiple callbacks to conditionally prevent an object from being created (and sending back the appropriate error message when that’s the case):

Although the above code did work, the nested callbacks were a headache to look at and would be a pain to ever have to alter down the road.

Enter promises.

I had always heard of promises, and understood them conceptually: they strive to eliminate pyramid code by allowing for the chaining together of callbacks. This seemed like the perfect use-case for me to finally get my hands dirty. After some deep googling / StackOverflow, promises came to the rescue:

Ahh, much better! https://gist.github.com/vikdenic/a1f07fee9f319027923a

I am able to retrieve the data and set the variables right off the bat using .then chaining. I then make sure that all my promises return something to the next.

The .then chaining aligns the code very nicely, and the logical flow of “promised” returns from one promise to the next makes it very readable.

--

--