Promises also have a catch()
method that behaves the same as then()
when only a rejection handler is passed.
For example, the following `catch()
` and `then()
` calls are functionally equivalent:
promise.catch(function(err) { // rejection//from w w w . j av a 2s .c o m console.error(err.message); }); // is the same as: promise.then(null, function(err) { // rejection console.error(err.message); });
We can add new fulfillment and rejection handlers at any time and guarantee that they will be called.
For example:
let promise = readFile("example.txt"); // original fulfillment handler promise.then(function(contents) { console.log(contents);/*from www . j a v a2s. c o m*/ // now add another promise.then(function(contents) { console.log(contents); }); });
In this code, the fulfillment handler adds another fulfillment handler to the same promise.
The promise is already fulfilled at this point, so the new fulfillment handler is added to the job queue and called when ready.