The point of promises, as explained in this article, is to mirror the error handling semantics of synchronous code with minimal boilerplate.
In code based on callbacks, if an error occurs somewhere, you must either deal with it locally or pass it along the callback chain manually. Promises mimic the try/catch system.
Here's a variation based on the first example in the WhenJS documentation[0]. It demonstrates the basic control flow, we'll see later why it makes error handling easier:
function loadImage (src) {
var deferred = when.defer(),
img = document.createElement('img');
img.onload = function () {
deferred.resolve(img);
};
img.onerror = function () {
deferred.reject(new Error('Image not found: ' + src));
};
img.src = src;
// Return only the promise, so that the caller cannot
// resolve, reject, or otherwise muck with the original deferred.
return deferred.promise;
}
// example usage:
loadImage('http://google.com/favicon.ico').then(
function gotIt(img) {
document.body.appendChild(img);
return aSecondPromise;
},
function doh(err) {
document.body.appendChild(document.createTextNode(err));
}
).then(function(/*resolved value of the second promise*/){...});
First, lets focus on the `loadImage()` function, which wraps an async image load into a promise object.It first creates a deferred object wich has two methods and one property:
* `defered.promise` is an objet with a `then` method that takes two optional handlers (success,error), which returns another promise. This allows chaining (more on that later).
* `defered.resolve(result)` resolves the corresponding promise: it takes one parameter and passes it to the success handler.
* `reject(error)` has similar behaviour but for the error handler.
These two methods are mutually exclusive. If you call one, you can't call the other.
As you can see, `loadImage()` defines two event handlers for the img object, that will either resolve or reject the promise. It schedules the async event, then returns the promise object. The `then` method of the latter registers two handlers one of which will kick in when the async call resolves the promise.
--
There's no point in using promises for trivial code like this.
Their usefulness comes from subtleties in the way the `then()` methods propagate the successes and errors when they are chained.
Success and error handlers are optional. If at a given step a success/error should have been triggered but isn't, the value is passed to the next one of the same kind in the then chain.
Let's take the example in this article:
getTweetsFor("domenic") // promise-returning async function
.then(function (tweets) {
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning async function
})
.then(doHttpRequest) // promise-returning async function
.then(
function (responseBody) {
console.log("Most recent link text:", responseBody);
},
function (error) {
console.error("Error with the twitterverse:", error);
}
);
At each step, the promise can be resolved or rejected. If it is resolved, its result is passed to the next success handler. If if is rejected at any step, the following OK steps are skipped, and the error ends up being handled by the error handler defined in the last then clause. It is thus equivalent to this synchronous code: try {
var tweets = getTweetsFor("domenic"); // blocking
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
var responseBody = doHttpRequest(expandUrlUsingTwitterApi(mostRecentShortUrl)); // blocking x 2
console.log("Most recent link text:", responseBody);
} catch (error) {
console.error("Error with the twitterverse: ", error);
}
Imagine how messy it would be to propagate the errors in standard callback-based code...--
One last thing about handlers:
loadImage(src).then/*1*/(successH, errorH).then/*2 */(successH2, errorH2);
loadImage() returns a first promise and its `then1()` method registers the handlers and returns a promise, whose state will depend on the behaviour of the handlers once one of them is triggered. If the handler (either successH or errorH) returns a value, the promise will pass that value to the next success handler. If the handler throws an exception, the value thrown will be passed to the next error handler, and so on.This brings us the following parallel, FTA:
1. Promise fulfilled, fulfillment handler returns a value: simple functional transformation
2. Promise fulfilled, fulfillment handler throws an exception: getting data, and throwing an exception in response to it
3. Promise rejected, rejection handler returns a value: a catch clause got the error and handled it
4. Promise rejected, rejection handler throws an exception: a catch clause got the error and re-threw it (or a new one)
At last, a handler can return a new promise. In that case, the handler that is called next will depend on whether that promise is resolved or rejected.
--
Sigh... I'm done. I hope I didn't make things more confusing.
--