The Promise then()
method takes two arguments.
Parameter function | Meaning call when the promise is fulfilled. Any additional data related to the asynchronous operation is passed to this fulfillment function. |
---|---|
function | call when the promise is rejected. the rejection function is passed any additional data related to the rejection. |
Any object that implements the then()
method this way is called a thenable
.
All promises are thenables, but not all thenables are promises.
Both arguments to then()
are optional.
We can listen for any combination of fulfillment and rejection.
For example, consider this set of then()
calls:
let promise = readFile("example.txt"); promise.then(function(contents) { // fulfillment console.log(contents);// www. j a v a2 s .c o m }, function(err) { // rejection console.error(err.message); }); promise.then(function(contents) { // fulfillment console.log(contents); }); promise.then(null, function(err) { // rejection console.error(err.message); });
All three then()
calls operate on the same promise.
The first call listens for both fulfillment and rejection.
The second only listens for fulfillment; errors won't be reported.
The third just listens for rejection and doesn't report success.