Introduction

Who Is This Guide For

This guide is primarily for experienced JavaScript/Node developers who are familiar with asynchronous callbacks and are looking to quickly master an alternative way of asynchronous programming in JavaScript i.e. Promises and Async/Await. It can also be useful for novice JavaScript developers, moving from other languages and trying to master the promise-based programming model in JavaScript.

It's been our experience that information about Promises in Javascript is scattered across many online tutorials + books and is generally hard to make sense of – sometimes diving into history and deep details of implementation, other times: not giving enough depth to be productive. In contrast, our goal was to create a clear and simple guide that can help you master practical programming with Promises. We intend to skip on the complicated and messy history of Promises in JavaScript and the nitty-gritty details of how they are implemented.

Benefits Of Using Promises - Why Should You Care?

If you are to go through a fundamental change in how you write asynchronous code in JavaScript, we should explain why such change is worth your time and headache. There are three major benefits to using Promises:

  1. Promises provide you a clean, native and standard way to execute several asynchronous tasks in parallel and only move to the next task once at least one or all of the parallel tasks are successfully completed. Without promises you may have used Async.some and Async.parallel methods from the popular Async library, for achieving the same.

  2. Promises provide cleaner error-handling that feels like traditional try... catch, from synchronous programming, and allows you to easily bubble exceptions up the execution chain, if needed.

  3. Promises provide asynchronous code syntax that people generally find cleaner than callbacks when chaining multiple asynchronous calls.

Side note: while "cleaner syntax" is the most frequently cited benefit of Promises, it may or may not be the most important one, for you. Syntax alone is a matter of preference and changing habits may not outweigh the benefits. However, as noted above, there are reasons to adopt Promises that go beyond just "syntax".

Prerequisites

To use Promises natively you need a modern JavaScript implementation, namely ECMAScript 2015 (6th Edition, ECMA-262) or later. Such version can be found in Node v6, or later, and in most modern browsers. If you are dealing with an older JavaScript/ECMAScript version you can transpile it using Babel.

It is also common to add or augment Promises support by using powerful third-party libraries such as BlueBird or Q. Currently these libraries implement wider functionality than what is found in the native implementation and a lot of people use them even with the latest versions of ECMAScript. We like BlueBird.

Last updated