HTML and CSS Reference
In-Depth Information
/* ... */
}.bind(this));
return promise;
}
Yet another converted test passes. Converting the remaining tests should be
fairly straightforward, so I will leave doing so as an exercise. Once all the tests have
been updated, we need to decide whether or not we should remove the callback.
Keeping it will allow users to decide which pattern they prefer to use, but it also
means more code to maintain on our part. Because the promise handles all the
callbacks for us, removing the manual callback means we don't need to concern
ourselves with whether or not it was passed, if it's callable, and so on. I recommend
relying solely on the promises.
14.4.2 Consuming Promises
Now that the addMessage method uses promises we can simplify code that needs
to add more than one message. For instance, the test that asserts that each message
is given its own unique id originally used nested callbacks to add two messages and
then compare them. Node-promise offers an all function, which accepts any
number of promises and returns a new promise. This new promise emits success
once all the promises are fulfilled. We can use this to write the unique id test in
another way, as seen in Listing 14.52.
Listing 14.52 Grouping promises with all
/* ... */
var all = require("node-promise/promise").all;
/* ... */
testCase(exports, "chatRoom.addMessage", {
/* ... */
"should assign unique ids to messages": function (test) {
var room = this.room;
var messages = [];
var collect = function (msg) { messages.push(msg); };
var add = all(room.addMessage("u", "a").then(collect),
room.addMessage("u", "b").then(collect));
 
Search WWH ::




Custom Search