Reputation: 726
Example 1
function first(a, b) {
return a + b;
}
function second() {
return Math.floor(Math.sqrt(arguments[0]));
}
function third() {
return Math.PI * (arguments[0]);
}
Q.fcall(first, 3, 4)
.then(second)
.then(third)
.then(function (result) {
console.log(result);
});
Example 2
function first(a, b) {
var d = Q.defer();
if (isNaN(a) || isNaN(b)) {
d.reject('Wrong Numbers');
} else {
d.resolve(a + b);
}
return d.promise;
}
function second() {
return Math.floor(Math.sqrt(arguments[0]));
}
function third() {
return Math.PI * (arguments[0]);
}
first(3, 4)
.then(second)
.then(third)
.then(function (result) {
console.log(result);
}, function (error) {
console.log(error);
});
So what is the difference between this 2 examples, because from what i could understand on my own, was that with Example 2, we have error and success handlers and in Example 1 we don't
Upvotes: 4
Views: 401
Reputation: 2259
The two examples are analogous, however, in the first example you are adapting a non-promise based function, whereas the second directly returns a promise. If you are writing your own functions where you always want to return promises your second example would be prefered. However, this, of course, comes at the cost of adaptability if the functions are to be used in a non-promise based context. Q.fcall
is more commonly used to adapt third party functions to the promise based paradigm.
Here's a third example you could also use (this is my prefered way of doing things when writing a promise based library):
function first(a, b) {
if (isNaN(a) || isNaN(b)) {
return Q.reject('Wrong Numbers');
} else {
return Q(a + b);
}
}
function second() {
return Q(Math.floor(Math.sqrt(arguments[0])));
}
function third() {
return Q(Math.PI * (arguments[0]));
}
first(3, 4)
.then(second)
.then(third)
.then(function (result) {
console.log(result);
})
.fail(function (error) {
console.log(error);
});
This removes some unnecessary calls to Q.defer()
by using the following:
Q(value)
If value is a Q promise, returns the promise.
If value is a promise from another library it is coerced into a Q promise (where possible).
If value is not a promise, returns a promise that is fulfilled with value.
Q.reject(reason)
Returns a promise that is rejected with reason.
It is also worth noting that Q contains a whole host of methods to adapt different types of functions, methods, nodejs style callbacks etc. to the Q promise based system. Many of these are not mentioned in the readme, instead check the API reference.
Upvotes: 2