JS承诺:然后和捕获之间有什么区别

JS Promises: What is the difference between then and catch

本文关键字:之间 什么 区别 承诺 然后 JS      更新时间:2024-06-17

我正在尝试重新实现promise库。根据我的理解,then会监听promise状态何时更改,并根据结果执行成功回调或失败回调。从MDN文档来看,catch似乎与错误解决有关——不过我认为这就是为什么。它们之间有什么区别?

这是我当前的代码:

//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;

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

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