Javascript – Is there something a `Promise` can do that `async` cannot

javascript

Recently, I've spent a lot of time trying to dive into, and understand, Javascript Promises, especially those adhering to the Promises/A+ spec. What I'm trying to understand is whether or not Promises actually give developers additional tools specifically when compared to CPS based async, or whether it is mostly syntactic sugar and a tool to reduce verbosity or streamline some behaviors.

One argument I've heard for promises is error handling. In that case, using the async library it is very easy to execute a async.waterfall of functions, each waiting for the prior to complete, each wrapped in a try/catch to handle synchronous errors (since neither Promises, nor async handle async errors), passing caught errors to an error handler. In that situation Promises and async behave identically regarding error semantics (gist showing this behavior).

Another argument I've heard for promises is future-proofing methods which are sync now, but asynchronous later on. The theory is that if the function returns a promise, it doesn't matter what if it is modified later. Since both sender and receiver have to modified to adhere to the promise contract, can't the same argument be stated for modifying both sender and receiver to use the CPS contract, even if it's synchronous, to future proof it?

So with that in mind is there any use-case that you can think of which can only be solved optimally by Promises or is their usage really more a case of preference and the desire to reduce verbosity and reduce the chance of error?

Best Answer

Some of the advantages of promises are that they make asynchronous operations a "first-class" entity. They can be transformed, they are composable, and their use also happens to reduce nesting and make handling of async code more analogous to sync code. To me, it is usually more readable to have a chain of promises than nested callbacks. Many modern languages have moved to promise-style async.

See: http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/

Related Topic