News for hackers. Stuff that matters.
Re:Promises/A+ by domenicd on Monday July 08, 2013 @05:00PM (#6009259)
It's worth noting we are very close to finishing up a 1.1 revision of the spec, which clarifies a few things mainly around how promise libraries interoperate with each other's promises. You can find the work in our master branch (as opposed to gh-pages):

https://github.com/promises-aplus/promises-spec

Including a changelog:

https://github.com/promises-aplus/promises-spec/blob/master/...

And the issues still open versus closed in the 1.1 timeframe are at

https://github.com/promises-aplus/promises-spec/issues?miles...

We were hoping to do a revision of the website's look at the time of the 1.1 release as well, mainly adding links to additional resources in the repository (like the implementations list, credits, etc.). A bit sad that we haven't moved fast enough to finish that before making the front page of Hacker News!

Re:Promises/A+ by SeanDav on Monday July 08, 2013 @04:26PM (#6009059)
I have just started doing development in Node.js. Originally using the excellent caolan/async library (https://github.com/caolan/async) for handling synchronous situations. Now started moving towards Promises but finding it quite hard to locate any "Promises for Dummies" type guide. Most of the libraries like "q" etc (https://github.com/kriskowal/q) just give you a list of functions to use and related syntax but I have yet to come across a guide that goes into detail as to exactly how and why you use certain functions.

I am kind of figuring things out as I go along but if anyone here can point me to such guides, I would be most grateful.

Re:Promises/A+ by domenicd on Monday July 08, 2013 @04:53PM (#6009208)
I have given several talks, for which slide decks and one video are available:

http://www.slideshare.net/domenicdenicola/callbacks-promises...

http://www.slideshare.net/domenicdenicola/promises-promises with video at http://www.youtube.com/watch?v=MNxnHbyzhuo

http://www.slideshare.net/domenicdenicola/boom-promisesa-was... which is more inspirational and motivational than practical

Otherwise, in the Q readme we try for a "graduated tutorial" approach; would welcome any feedback you have to make it more friendly. We try to relegate the "list of functions" to the API reference at https://github.com/kriskowal/q/wiki/API-Reference

Re:Promises/A+ by SeanDav on Monday July 08, 2013 @05:02PM (#6009274)
Hi Domenic, Thanks for those links - I will check them all. There is another one of yours (co-speaker) that I thought was excellent: Redemption from Callback Hell (http://www.youtube.com/watch?v=hf1T_AONQJU)
Re:Promises/A+ by domenicd on Monday July 08, 2013 @05:42PM (#6009530)
Oh yes, I always forget about this one because it's not on my SlideShare, but you're right, it's really excellent! Michael did a great job putting that together and I was honored he invited me to share the stage.
Re:Promises/A+ by DanielRibeiro on Monday July 08, 2013 @05:29PM (#6009449)
James Coglan did a good introduction of promises on his Callbacks are imperative, promises are functional: Node’s biggest missed opportunity[1] (HN discussion here[2]).

The author of Promises/A+ also wrote a nice blost post on his You're Missing the Point of Promises [3]

Promises are actually a part of a of a very well understood programming mechanism that involves Futures and Deferred as well[4]

[1] http://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-...

[2] https://news.ycombinator.com/item?id=5466872

[3] https://gist.github.com/domenic/3889970

[4] http://en.wikipedia.org/wiki/Future_%28programming%29

Re:Promises/A+ by SeanDav on Monday July 08, 2013 @08:15PM (#6010311)
>Promises are actually a part of a of a very well understood programming mechanism that involves Futures and Deferred as well

This is my problem - when I last formally studied Computer Science we never covered this. I think most, if not all, of the Promises libraries assume you have a background that covers this, which makes it harder for those of us who have to work out all this from scratch. Not that I am complaining - just an observation.

Probably also harder for people like me that are not working with anyone who actually knows Node.js or Promises. The upside is of course that knowledge gained the hard way often sticks better, even if the process is more frustrating.

Re:Promises/A+ by lightblade on Tuesday July 09, 2013 @03:49PM (#6014922)
I think promises are easy to understand.

Lets start with the most basic element of a promise: the `then` method. It is so basic in fact, that the spec only covers on how this method should behave and nothing else. All the other functions that you see in the libraries (Q, whenjs, etc) just have a lot of combinator functions that's built on top of the `then` method. Take the `Q.all` for example, it functions the same `then` except it wait for all promises passed into to it to finish before continuing with its own `then`. So understanding how the `then` behaves is essential to understanding promises.

IMO, the advantage of using promise is how composable it is. To achieve desired effect, you can take a few existing promise combinators, compose them together with just object/array literals and function calls.

For example, the other day I needed a html form to submit with a load mask covering the form while waiting for the submission to complete. The problem is that this submission can take anywhere from 21ms to 1500ms to complete. In order to achieve good UX, I needed the load mask to be not just a flash in the extremely fast case, but also not taking more than necessary time to complete in the extremely slow case. So I did this...

Q.all([ asyncFormSubmitReturnPromise(), Q.delay(500) ]).then(function() { // hide mask & other cleanup })

For comparison, to achieve the same effect using asyncjs...

async.parallel([ function(callback){ asyncFormSubmit({ success: callback }) }, function(callback){ setTimeout(callback, 500) } ], function(err, results){ // hide mask and cleanup })

I want to mention another advantage with promises: it creates an uniformed interface that disregards whether the loading is synchronous or asynchronous. Say for example you're writing a select box widget that needs to populate the dropdown's content. Your widget can expose a method just called `load` and it takes a promise. Now whoever is calling your `load` method will have the total freedom to pass in a promise's already resolved or pending to be resolved. If you have the data at hand, it's just as easy to wrap it in a promise `Q.resolve(data)` and pass it in.

Re:Promises/A+ by 1qaz2wsx3edc on Monday July 08, 2013 @10:59PM (#6010842)
People like you? People that haven't studied CS?

Hmm, let me check, yup. I understand promises fully.

Anywho. They are not hard to learn. Watch a few videos. James Coglan talks are excellent, watch twice even.

Finally if you don't like a library, find another, see if the glove fits.

Re:Promises/A+ by tgriesser on Monday July 08, 2013 @05:20PM (#6009394)
I recently wrote two Node.js libraries that use promises extensively, an Active Record style ORM http://bookshelfjs.org and Query Builder http://knexjs.org. I actually didn't find a need for many of the higher level functions, outside of .then I'd typically stick to .all, .reject / .resolve, and occasionally .defer.

The source should be fairly annotated and is structured similar to Backbone.js, so it might be useful to take a look through and see where/how those functions are being used.

Re:Promises/A+ by dclowd9901 on Monday July 08, 2013 @07:08PM (#6009994)
The thing about promises is their real power comes when you return them out of functions you run, thus causing any function to become async, and the promise being returned allows it to be used in a variety of ways:

    promisesFunc().done(function(){ // execute on completion }

    q.when(promisesFunc).then( function(){ // do stuff } )
It's nice to be able to treat something that is inherently asynchronous like it is inherently asynchronous. Feels good man.jpg. And just wait til you start mixing in generators (well, eventually).
Re:Promises/A+ by _greim_ on Monday July 08, 2013 @04:04PM (#6008927)
My beef with JS Promises (uppercase "P") is that, as a programming idiom, I prefer once I have X, Y and Z, do something with X, Y and Z over get X, then get Y, then get Z. In the former case, the provisioning logic is a separate concern; it could be done in parallel, serially, or via some combination of both. In the latter case, it's inherently serial.

I wrote an alternate implementation of promises in JS (lowercase "p") that uses the former approach: https://github.com/greim/await.js

Re:Promises/A+ by tlrobinson on Monday July 08, 2013 @04:45PM (#6009166)
It's absolutely possible to do multiple things in parallel using Promises/A(+) then "resolve" a new promise once they're all done. That's what Q.all() in the Q library does, for example.

That API isn't written into the Promises/A+ spec because it doesn't need to be. That spec is the minimal things necessary for multiple promise implementations to be interoperable.

Re:Promises/A+ by ufo on Monday July 08, 2013 @04:31PM (#6009087)
Personally, that sounds like a really odd complaint to make. After all, running promises in parallel should be just a matter of using a simple library function that you can very easily code yourself if its not already provided.

I tend to find that the biggest problem with promise libraries is writing code with lots of jumps and more advanced control flow. If you are using an explicit continuation-based approach then doing a jump (for a loop or for breaking out early) is just a matter of calling the appropriate continuation. On the other hand, promises naturally tend to prefer the sort of code where there is only a single return statement at the end (unless you abuse the error handling system but there are all sort of problems if you do that)

Re:Promises/A+ by drhayes9 on Monday July 08, 2013 @04:29PM (#6009073)
I don't understand your comment (or this is related to the lack of good introductory material noted in another comment).

You can retrieve the results of promises in parallel, serially, or via some combination of both. That's part of their power versus straight callbacks which enforce a serial approach.

Check out this link to q's documentation: https://github.com/kriskowal/q#combination

Re:Promises/A+ by ufo on Monday July 08, 2013 @04:35PM (#6009112)
TBH, both callbacks and promises are kind of similar when it comes to running things in parallel. In both cases you use the same sort of semaphore pattern and its something thats easy to hide behind a library function.

    function parallelCallbacks(cbs, onAllDone){
        var nLeft = cbs.length;
        var results = []
        var onOneDone = function(res){
           results.push(res);
           nLeft -= 1;
           if(nLeft <= 0){ onAllDone(results) }
        }

        for(var i=0; i<cbs.length; i++){
            cbs[i](onOneDone);
        }
    }

    parallelPromises([
       function(){ return promise(10) },
       function(){ return promise(20) }
    ).then(function(results){ ... });

    parallelCallbacks([
        function(onDone){ onDone(10) },
        function(onDone){ onDone(20) }
    ], function(results){
       ...
    });
Re:Promises/A+ by tlrobinson on Monday July 08, 2013 @04:49PM (#6009184)
One of the main differences is in error handling. Much like exceptions, errors are automatically propagated to the first error handler in the promise chain. With Node-style callbacks you need to explicitly check for errors and re-emit them at every stage.

I also think promises' use of return values vs passing a callback as an argument is conceptually cleaner and easier to compose.

Re:Promises/A+ by ufo on Monday July 08, 2013 @05:00PM (#6009263)
Absolutely correct, I ommited error handling to keeop the example simple but error handling is definitely more natural in a promise setting because you don't need to make your own error callback protocol.

That said, I still feel that both promises and explicit callbacks kind of suck in their own way. Callback code is usually much more verbose and has bad error handling while promises are bad at "jumpy" control flow. When I last worked in a big JS project it got bad enough that I eventually wrote my own control flow library on top of the base Dojo promises we were using so nowadays if I had to work with a big JS project again I would definitely try to use of those tools that add async control flow to the language and compile doen to regular continuations (looks nice like promises, can use loops, break and return like regular JS and raw callbacks don't need extra runtime support)

Re:Promises/A+ by _greim_ on Monday July 08, 2013 @06:04PM (#6009663)
My main point is that Promises don't have any concept of parallelism; all() is specific to the Q library, not part of Promises/A+. Obviously that's the intent—low-level building blocks—but it leaves one feeling like Promises don't actually solve any hard problems. You still have to solve them yourself.
Re:Promises/A+ by jkrems on Monday July 08, 2013 @10:08PM (#6010665)
Promises/A+ is not a promise library. It's not a spec about "what should a promise library do". It's about interoperability - "how can I exchange data AND promises between libraries without relying on a shared library/on everyone using the same library for flow control?". Also the spec makes error handling non-surprising, I don't need to read through the docs of a library to know how errors propagate. It looks like your promise library would have been easy to make comply with the spec by just calling "onkeep" "then" (and maybe adapting a few minor details).
Re:Promises/A+ by ufo on Monday July 08, 2013 @09:39PM (#6010574)
But callbacks also don't have any concept of paralelism and its trivially easy to code all() yourself once and then forget about it.

The hard problem that promises solve are

1. Its more similar to regular code versus explicit CPS (no pyramid of doom, use "return" to return values, can store promises in data structures or pass them around to other functions)

2. Error handling. Regular Javascript has try-catch blocks for exception handling but those don't work with async code. Promises let you use exceptions in async code without having to worry about error callbacks.

Re:Promises/A+ by andywhite37 on Monday July 08, 2013 @04:34PM (#6009105)
I like your approach with your await library. You're probably aware of this, but the jQuery "Deferred" implementation of promises has a similar mechanism that I'm not sure is common in other JavaScript promise implementations:

$.when()

http://api.jquery.com/jQuery.when/

Re:Promises/A+ by jasondenizac on Monday July 08, 2013 @04:48PM (#6009182)
Q has `Q.all()` which does the same thing: https://github.com/kriskowal/q/wiki/API-Reference#promiseall
Re:Promises/A+ by andywhite37 on Monday July 08, 2013 @05:44PM (#6009544)
Oh that's cool, thanks for the reply. I haven't looked at Q yet, but I've heard a lot about it. I guess it's time to have a look.
Re:Promises/A+ by tjansen on Monday July 08, 2013 @05:31PM (#6009465)
The great thing about Promises/A+ is that it's so small. I have implemented it in 375 bytes, and was even able to add two convenience functions: https://github.com/timjansen/PinkySwear.js
Re:Promises/A+ by scotth on Monday July 08, 2013 @05:59PM (#6009630)
Great project name.
Re:Promises/A+ by domenicd on Monday July 08, 2013 @05:02PM (#6009273)
I gave a talk at JSConf US 2013 about the genesis of this spec, and how I believe it plays into the future of open, developer-driven APIs for the web platform. I hope the video is up soon, but until then, the slides are at http://www.slideshare.net/domenicdenicola/boom-promisesa-was...
Re:Promises/A+ by martingordon on Tuesday July 09, 2013 @12:08AM (#6011044)
Maybe I'm missing something, but I find C#'s async/await much more intuitive (not having written any C# and currently working on a pet project using promises with Node and Q).

My issue with promises is that I find myself working around the API/language when I actually want synchronous code. My app calls a JSON API and then writes the results to three tables (in sequence). In "normal", blocking code:

  results = getResults(); writeTable1(results.foo); writeTable2(results.bar); writeTable3(results.baz);
Using Node and Q:

  db.load().then(()-> setupDB(db)).then(()-> collectData(db)).done()
In which setupDB() returns a chain of three promises and collectData, which loops through the results and attach a new promise to the chain in order to return a chain of `n` promises.

Are these just growing pains of learning a new paradigm or am I using the wrong tool for the job?

Can someone point me to any projects that actually use promises?

Re:Promises/A+ by ShellfishMeme on Tuesday July 09, 2013 @08:21AM (#6012255)
If you make your `db.load` method resolve the promise with `this` (where `this` is `db`), and do the same for `setupDB` and `collectData` you can easily chain them without having to have a reference to `db`.

    db.load()
        .then(setupDB)
        .then(collectData);
That way it looks much more like your blocking code.

You are currently basically throwing away the value you `resolve` with, where you should instead resolve with what would be the return value if it was a sync function so you can `.then` the function that takes the return value and returns a promise to be resolved with its return value.

    // Sync
    var foo = function () { return 'foo' };
    var addBar = function (foo) { return foo + 'bar'; }
    addBar(foo()) == 'foobar'

    // Promise using Q
    var foo = function () { return Q.resolve('foo') };
    var addBar = function (foo) { return Q.resolve(foo + 'bar'); }
    foo.then(addBar).done(function (result) {
        result == 'foobar'
    });
Re:Promises/A+ by domenicd on Tuesday July 09, 2013 @10:48AM (#6012917)
It's worth noting that C#'s async/await is based directly on promises; they are called `Task<T>` in .NET. Indeed, they share a common ancestor I believe; .NET 4.5's `Task<T>` is derived from F#'s `Async<T>`, and both `Async<T>` and JavaScript promises are based on E's promises.
Re:Promises/A+ by martingordon on Wednesday July 10, 2013 @10:16AM (#6019734)
Yeah, I think the big difference for me is the language support. You can just await a method call instead of having to wrap the remainder of your block in a function.

Perhaps I should look into IcedCoffeeScript (http://maxtaco.github.io/coffee-script/) instead of plain CS.

Re:Promises/A+ by kolodny on Monday July 08, 2013 @03:57PM (#6008893)
I wrote a library a while ago that nearly fulfills this entire spec. I've added/changed things that I thought were more intuitive. https://github.com/kolodny/wttt
Re:Promises/A+ by jkrems on Monday July 08, 2013 @09:57PM (#6010637)
The point of having the spec is that libraries can freely exchange data and promises, even if they depend on totally different flow control libraries, while still being certain that error handling and chaining works as expected. It looks like if I build on top of your library, I'm locked in.

This is not to say that it invalidates your library or that every promise library has to comply to A+ or that A+ is the only good way to design promises in JS.

Re:Promises/A+ by willvarfar on Monday July 08, 2013 @05:42PM (#6009532)
> 3.2.1.1 If onFulfilled is not a function, it must be ignored.

This is idiomatic JS I guess, but it bugs me to bits. IMO the parameter should be a function or it should be null; anything else should throw an error.

Re:Promises/A+ by domenicd on Monday July 08, 2013 @07:29PM (#6010090)
`then` is meant to return a promise, i.e. return an asynchronous value; it should never synchronously throw an error.

That said, I somewhat agree (although in JavaScript it should be `undefined`, not `null`). If we were starting clean, instead of with tons of code in the wild that did `.then(null, onRejected)` or `.then(false, onRejected)`, we would have the resulting promise be rejected with a `TypeError` if `onFulfilled` was neither `undefined` nor a function.

Re:Promises/A+ by willvarfar on Tuesday July 09, 2013 @01:13AM (#6011227)
Hmm null is easier to pass on purpose and undefined is easier to pass by accident.

Sending in undefined for a non-trailing argument takes effort.

I think the literal null is far more communicative of the developers intent.

But the general point is, JS APIs tend to fail silently on error by design and that's something that bugs me, literally. Bugs. Lots of them.

I agree regards returning a failure rather than throwing an exception, though.

Re:Promises/A+ by unwiredben on Tuesday July 09, 2013 @01:45AM (#6011292)
Thanks for this discussion... after reading Domenic's slides, watching his talk, and going through the questions here and on the gist, I've filed a bug to try to move Enyo's async implementation to promises after our next release. (https://enyojs.atlassian.net/browse/ENYO-2700) Currently, our code is more like the jQuery 1.5 implementation, but it really lacks the nice error semantics that Promises/A+ has.
Re:Promises/A+ by andrewcooke on Monday July 08, 2013 @03:24PM (#6008662)
wouldn't it be good to explain somewhere, early on, that this is for javascript?
Re:Promises/A+ by domenicd on Monday July 08, 2013 @04:50PM (#6009192)
This is actually a really good point, haha! Filed, and will fix in the upcoming so-close-to-done 1.1 revision: https://github.com/promises-aplus/promises-spec/issues/135
Re:Promises/A+ by jasondenizac on Monday July 08, 2013 @04:51PM (#6009196)
While the Promises/A+ specification is primarily focussed on JavaScript, the concept of promises certainly did not originate in JavaScript. For that matter, there are actually a number of implementations of Promises/A+ in other languages and platforms: https://github.com/promises-aplus/promises-spec/blob/master/...
Re:Promises/A+ by __david__ on Monday July 08, 2013 @04:34PM (#6009107)
Well, the link in the first sentence does point to http://commonjs.org/...
Re:Promises/A+ by ricardobeat on Monday July 08, 2013 @07:55PM (#6010222)
Promises are coming of age too late, and still have unsolved fundamental issues.

Meanwhile, ES6 generators are coming to node v0.12, already in FF and soon to be in Chrome; that is a whole different game.

Re:Promises/A+ by 1st1 on Monday July 08, 2013 @09:17PM (#6010506)
It's still better to use promises as an underlying mechanism, so that you can "yield* promise" or "yield* generator". This approach is now implemented in python tulip framework, and it solves the problem of combining the existing callback-based code with coroutines.
Re:Promises/A+ by pspeter3 on Monday July 08, 2013 @04:59PM (#6009251)
Just out of curiosity, why don't we use node's event emitters to wrap callbacks as promises?
Re:Promises/A+ by jkrems on Monday July 08, 2013 @09:51PM (#6010613)
Because promises resolve to one value which can be retrieved long after the promise was resolved. This is a fundamentally different approach than EventEmitters. node's streams are the closest thing to "promise meets event emitter" I'm aware of. But maybe I'm missing the point of your question.