根据Understanding ECMAScript 6then接受2个参数。

The then() method is present on all promises and takes two arguments.
The first argument is a function to call when the promise is fulfilled. Any additional data related to the asynchronous operation is passed to this fulfillment function. The second argument is a function to call when the promise is rejected. Similar to the fulfillment function, the rejection function is passed any additional data related to the rejection.

而且可以酌情处理任一promise的状态:

let promise = readFile("example.txt");

promise.then(function(contents) {
  // fulfillment
  console.log(contents);
  }, 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);
});

但实际上,经常用then()来仅仅处理fullfillment状态,而用另一个函数catch()来处理rejection状态,所以这俩函数经常连用(chain)来完整处理一个promise,而且建议这么连用,哪怕catch()仅仅对err做了console.log(err)处理。

promise.catch(function(err) {
  // rejection
  console.error(err.message);
});

标签: promise, then

添加新评论