Over a million developers have joined DZone.

JavascriptPromise

· Web Dev Zone

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

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.



Make the transition to Node.js if you are Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Martin Fowler, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}