【问题标题】:JS Promises: What is the difference between then and catchJS Promises:then 和 catch 有什么区别
【发布时间】:2015-04-29 09:25:42
【问题描述】:

我正在尝试重新实现承诺库。据我了解,then 会监听 Promise 状态何时发生变化,并根据结果执行成功回调或失败回调。从 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;

【问题讨论】:

标签: javascript promise


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2013-09-18
    • 2013-11-09
    • 1970-01-01
    • 2013-10-27
    • 2016-04-20
    相关资源
    最近更新 更多