The benefit of using promises is just that they provide a powerful, common interface for async tasks.
The main benefit of a common interface (any common interface) is that you can write and use higher-level functions that operate on promises. As just one example, many promise libraries provide a function, often called all
, that takes a set of promises, and returns a new promise that encapsulates all of them. Then you can write things like:
promise.all(promise1, promise2).then(function (value1, value2) {
// blah blah
});
instead of this pyramid code
promise1.then(function (value1) {
promise2.then(function (value2) {
// blah blah
});
});
And of course you can only use functions like all
if you're using async tasks with some known, common interface. It would be impossible if some had .then
methods, some had .success
methods, and so on.
The promise
interface has other useful properties, for instance the .then
method on a promise returns a promise - and if the callback you pass it returns a promise, the .then
method returns a promise that actually awaits the promise returned by the callback. In other words:
// p1 is a promise that resolves to 1, when somePromise resolves
var p1 = somePromise.then(function (value) {
return 1;
});
// p2 is a promise that resolves to what someOtherPromise resolves to,
// not to someOtherPromise itself
var p2 = somePromise.then(function (value) {
return someOtherPromise;
});
Which makes it nice and easy to make a series of HTTP calls, one after another.
There are some drawbacks to using promises too... By convention, they wrap your callback in a try/catch block, so if you throw an exception it will be caught, sometimes invisibly.
somePromise.then(function (value) {
throw 'error';
}).catch(function (error) {
// without this catch block, the error may be eaten invisibly
console.error(error);
});
To sum up, a promise is just a widely-used interface for managing asynchronous tasks. Use it if you want, don't if you don't.