News for hackers. Stuff that matters.
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)