HTML5 Zone is brought to you in partnership with:

I am an author, speaker, and loud-mouth on the design of enterprise software. I work for ThoughtWorks, a software delivery and consulting company. Martin is a DZone MVB and is not an employee of DZone and has posted 80 posts at DZone. You can read more from them at their website. View Full User Profile

JavascriptPromise

04.25.2013
| 2300 views |
  • submit to reddit

In Javascript, promises are objects which represent the pending result of an asynchronous operation. You can use these to schedule further activity after the asynchronous operation has completed by supplying a callback.

    aPromise = someAsyncOperation();
    aPromise.done(function() {
      // runs if all went well
    });
    aPromise.fail(function() {
      // runs if something went wrong
    });
    aPromise.always(function() {
      // runs either way
    }); 

As well as providing a clear interface to schedule activity with asynchronous tasks, they also compose.

      composedPromise = $.when(anAsyncFunction(), anotherAsyncFunction());

In this form (using jQuery promises) the composed promise will run its done handlers when all the passed promises succeed and its fail handlers if any of them fail.

There are various forms of promises in javascript, annoyingly they have subtly different APIs and vocabularies. Probably the most used is jQuery's Deferred Object.

You also hear these concepts described as futures and deferreds. These concepts appear in many languages, not just javascript, often with concurrency in mind as much as asynchrony.

For more information I suggest getting a copy of Trevor Burnham's Async JavaScript. If you want a web article, I found Burnham has a short but useful article summarizing them.



Published at DZone with permission of Martin Fowler, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)