JavaScript Promises – a meetup and an example

The Colombo JavaScript Meetup group organised an event titled ‘JavaScript Promises’ on 20 October, 2016 at WSO2, Colombo 3.


The two speakers – Isuru and Raathigeshan were both from Zone 24×7. Below are some of the notes I took from the two talks.

The old school way

Synchronous programming is when the code runs statement by statement, only running the following statement when the current one is completed.

Isuru began the talk introducing the Synchronous (old school) way of coding - when receiving data from an API endpoint for example. The solution was to google and go to stackoverflow only to come back and write a setTimeout().

The problem with this approach is that when the synchronous function is huge, this would freeze the application.

The (traditional) Asynchronous way

Asynchronous JavaScript essentially is when a code is not blocked by something that is to be completed. The page can load and wait for whatever is to be received - maybe some data through an API call. After the return is successful, a callback is made which would typically build the HTML based on the returned data.

Yes, you have achieved non blocking calls. Awesome!

Or is it? While this does ensure an async way of doing things, this way also has a couple of drawbacks:

  • Callback Hell - when chaining an absurd number of callback functions. After some time, the code would grow more horizontally than vertically  - and that is not a good thing. This problem is also known as The Pyramid of Doom 🙂
  • The stack/return could be lost, which could throw errors
  • The callback may execute multiple times

Enter Promises

The purpose of this blog post is not to lecture you on Promises. There are other awesome ways you can learn about it- like this one.

However, two things make promises useful and different from event listeners:

  • A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
  • If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

An example with Promises

The code below is a simple representation of how Promises can be implemented without any libraries since the current browsers already have support for it.

This works on Google Chrome 54, Mozilla Firefox 49 and Microsoft Edge 38.

fetch() is a method which is natively supported in modern browsers. It allows us to fetch data from API endpoints (duh).

The then() method is called with a promise and it takes two optional arguments - a success callback and a failure callback.

The catch() block is used to handle errors as you might have guessed it already.

Promises allow chaining - to link one then method to another - the return from the previous is the argument for the next - which is a way to condense our code. Combine this with ES6 Arrow functions and we have a lot done in a few lines of code.

baconipsum.com has a JSON API REST interface for generating meaty lorem ipsum text and can be used by any application. It returns a JSON string array of paragraphs and can be accessed via https.

In the above example, the fetch method receives the result as a response object,

  • then converts it into an JSON object - which contains a single array,
  • then into a string - which contains a long string of sentences separated by a period,
  • then splits the string into an array where there are periods
  • then prints each item in that array as a list item

You can notice that the promise gives us a clean way to code subsequent steps - in a story-telling fashion.

The future - async/await

Lastly, the speakers touched on this new way to do what we did in promises. Added in ES7 (ES2016), it is supposed to give us the benefits of synchronous programming when writing code in an asynchronous way, such as the ability to use try/catch. It is supported by Babel and Chrome 55.

I have to understand it myself properly to explain further. I hope to try this once I fully understand promises.

Conclusion

In short, the meetup was indeed useful as #CMBJS meetups usually are - in reigniting our love for JS. This was a blog post I promised myself 12 days ago.