JavaScript is single threaded, causing code to execute from top to bottom, so two bits of code cannot run at the same time. For example, you might download a JSON file from an (external) server and you’d have to wait until you retrieve that file. Instead of blocking the thread, there are ways you can streamline this code execution by using asynchronous JavaScript.

You’re probably already familiar with asynchronous JavaScript. Events (observer pattern) and Callbacks are examples of asynchronous code. For example, whenever you make an Ext.Ajax request or a user presses a button, the action is pushed into a queue, which is called the event loop. The JavaScript engine doesn’t start processing the event loop until the code has been executed after an async function (from top to bottom). This means that JavaScript code is not multi-threaded even though it appears to be so.

Callbacks are often used when you have an async operation (for example, loading data from a database) that should notify the caller about its completion. When calling such a function, you can pass it another function as an argument, which confirms that something has happened. Putting callbacks into callbacks is a great solution, and I think that’s one of the powerful features of JavaScript. However, it can be messy when your code requires other asynchronous pieces of code first.

For example, you read your user settings from local storage (that’s a callback!). Based on those settings, you make a request from some external server with a database connection, (that’s callback #2). Before you render that information on the screen, you retrieve something else from the database (that’s callback #3).

These steps are very common when you build a large enterprise app. In your code, there will be a callback function, written in a callback function, that’s in another callback function. You can imagine if these functions are spread over separate files that you’d have a hard time reading this code back a month later.

This is where JavaScript Promises comes into play. It’s a new way of writing your code in a more readable and understandable way. A Promise represents the result of a task, which may or may not have been completed. Like a contract for a value that we might not know when the promise is created. It’s an object or function with a then method. Because of the “then” method, the action can be chained endlessly, and that’s awesome!

A Promise typically has one of these 4 states.

  • fulfilled – when the promise succeeds
  • rejected – when the promise failed
  • pending – ongoing, hasn’t been fulfilled or rejected yet
  • settled – it has been fulfilled or rejected already

Lee Boonstra

Sencha

Lee is a sales engineer at Sencha in Europe. She’s located in Amsterdam and has experience in both front-end and back-end development. Lee spends her spare time developing web and mobile apps. She also wrote a book for O’Reilly: Hands-on Sencha Touch 2.