Update October 2018: If you need to brush up on promises and async/await, I highly recommend you look instead at my Mastering Asynchronous JavaScript course on Frontend Armory. The course contains 47 live examples and exercises, and also comes with this spiffy Promises and async/await cheatsheet.
Of course, my original promises guide is still useful today! Here it is:
Apart from being new and shiny, Promises are a great way to clean up your code, reduce dependencies on external libraries, and prepare yourself for async
and await
in ES7. Developers who use them swear by them, and developers who don’t just don’t know what they’re missing.
That said, promises can take a lot of work to understand. They feel completely different to the callbacks which we often use to accomplish the same thing, and there are a few surprises in their design which often cause beginners hours of debugging pain.
So why should I learn promises, again?
If the fact that promises are awesome doesn’t convince you, maybe the alternative to promises will.
Up until promises arrived, developers in JavaScript land had been using callbacks. In fact, whether you realise it or not, you’ve probably used them too! setTimeout
, XMLHttpRequest
, and basically all browser-based asynchronous functions are callback based.
To demonstrate the problem with callbacks, let’s do some animation, just without the HTML and CSS.
Say we want want to do the following: