Total Pageviews

Saturday, June 15, 2013

Promises, Promises

Async nightmares, the pyramid of doom, nested callback hierarchy, control flow: If you are familiar with any of these terms, you should be familiar with JavaScript promises.

As web apps get more sophisticated - and the use of JavaScript on the server continues to grow - there's an increasing need for an advanced way to handle flow control. Sometimes you find yourself with callbacks within callbacks within callbacks within callbacks (within callbacks). Other times you may have complicated business logic tangling up your code. Whatever your conundrum, you can use promises to simplify your code and make it more resilient.

Promises (also called deferreds or, even more confusingly, futures) is an approach in JavaScript where a flow is passed off to an object that is eventually either rejected (fail) or resolved (success). Any code waiting on a promise can then proceed based on the outcome.

The technique has been evolving over the last few years, and several libraries have been introduced. jQuery implemented Promises with version 1.5 (Jan. 2011), but most experts would advise you to use a library like Q, RSVP.js or when.js, even if you are already using jQuery. (jQuery's implementation is not optimal.)

Domenic Denicola, one of the contributors to the Promises/A+ spec, visited The Times to discuss his work, and we'd like to share his talk with you.

Guest speaker Domenic Denicola at the NYTimes developers' weekly JavaScript discussion.

In addition to being super smart, Denicola is also a really nice guy. He spends his days working at Lab49, and you can often catch him speaking at your favorite JavaScript conference. (At the recent HTML5Dev Conf, he gave a rousing rebuttal of RequireJS in favor of CommonJS.)



No comments:

Post a Comment