HTML and CSS Reference
In-Depth Information
14.4.1.2 Rejecting the Promise
Next up, we'll start changing the original tests to work with promises. The first test
we wrote expects addMessage to call the callback, passing an error if no username
is passed to it. The updated test can be seen in Listing 14.48.
Listing 14.48 Using the returned promise
"should require username": function (test) {
var promise = this.room.addMessage(null, "message");
promise.then(function () {}, function (err) {
test.isNotNull(err);
test.inherits(err, TypeError);
test.done();
});
}
The promise has a then method, which allows consumers to add callbacks to
be called when it is fulfilled. It accepts one or two functions; the first function is the
success callback and the second is the error callback. Another way of doing this is
to use the addCallback and addErrback methods, but I like the way “then”
reads: addMessage(user, msg).then(callback) .
To pass this test, we need to duplicate some efforts in addMessage , as we're
not yet ready to drop the old implementation. Listing 14.49 shows the updated
method.
Listing 14.49 Updating addMessage
addMessage: function (user, message, callback) {
var promise = new Promise();
process.nextTick(function () {
/* ... */
if (err) {
promise.reject(err, true);
}
}.bind(this));
return promise;
}
Here we call the promise's reject method, passing it an error. Normally,
the promise will throw an exception if reject is called and no error handler is
 
Search WWH ::




Custom Search