JS Promises:then和catch之间有什么区别

时间:2015-02-26 20:20:42

标签: javascript promise

我正在尝试重新实现promises库。根据我的理解,then监听promises状态何时更改并根据结果执行成功回调或失败回调。从MDN文档看来like catch has something to do with error resolution - 我认为这就是当时的情况。他们之间有什么区别?

这是我目前的代码:

//Not sure what this is for
var rejected = {}, resolved = {}, waiting = {};

var Promise = function (value, status) {


};


Promise.prototype.then = function (success, _failure) {
  var context = this;
  setInterval(function() {
    if (context.status) {
      success();
    } else if (success === undefined) {
      return;
    } else {
      _failure();
    }

  }, 100);
};


Promise.prototype.catch = function (failure) {
  return failure;
};



var Deferred = function (promise) {
  this.promise = promise || new Promise();
  this.promise.status = undefined;
};

Deferred.prototype.resolve = function (data) {
  this.promise.data = data;
  this.promise.status =  true;
};

Deferred.prototype.reject = function (error) {
  this.promise.data = error;
  this.promise.status = false;
};

var defer = function () {
  return new Deferred();
};


module.exports.defer = defer;

1 个答案:

答案 0 :(得分:1)

他们的工作方式没有太大区别。它们之间的唯一区别是catch不会success failure回调,而只会failure回调。它可以简单地实现为

Promise.prototype.catch = function(onFailure) {
    return this.then(null, onFailure);
};