The then
method returns a promise, which in this example, I’m assigning to outputPromise
.
var outputPromise = getInputPromise()
.then(
function (input) {
},
function (reason) {
}
);
The outputPromise
variable becomes a new promise for the return
value of either handler. Since a function can only either return a
value or throw an exception, only one handler will ever be called and it
will be responsible for resolving outputPromise
.
If you return a value in a handler, outputPromise
will get fulfilled.
If you throw an exception in a handler, outputPromise
will get rejected.
If you return a promise in a handler, outputPromise
will “become” that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.
If the getInputPromise()
promise gets rejected and you omit the rejection handler, the error will go to outputPromise
:
var outputPromise = getInputPromise()
.then(function (value) {
});
If the input promise gets fulfilled and you omit the fulfillment handler, the value will go to outputPromise
:
var outputPromise = getInputPromise()
.then(null, function (error) {
});
Q promises provide a fail
shorthand for then
when you are only interested in handling the error:
var outputPromise = getInputPromise()
.fail(function (error) {
});
If you are writing JavaScript for modern engines only or using CoffeeScript, you may use catch
instead of fail
.
Promises also have a fin
function that is like a finally
clause.The final handler gets called, with no arguments, when the promise returned by getInputPromise()
either returns a value or throws an error. The value returned or error thrown by getInputPromise()
passes directly to outputPromise
unless the final handler fails, and may be delayed if the final handler returns a promise.
var outputPromise = getInputPromise()
.fin(function () {
// close files, database connections, stop servers, conclude tests
});
outputPromise
outputPromise
gets postponed. The
eventual value or error has the same effect as an immediate return
value or thrown error: a value would be ignored, an error would be
forwarded.If you are writing JavaScript for modern engines only or using
CoffeeScript, you may use finally
instead of fin
.