1

I am trying to reimplement promises library. From my understanding, then listens to when a promises state changes and executes a success callback or failure callback depending on the results. From MDN documentation it seems like catch has something to do with error resolution- I thought this was what then is for though. What is the difference between them?

Here is my current code:

//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;
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100
  • Uh, there are many problems with your promise implementation. I suggest you read [this design guide](https://github.com/kriskowal/q/tree/v1/design), and [this](http://stackoverflow.com/q/17718673/1048572) or [that](http://stackoverflow.com/q/15668075/1048572) question. – Bergi Feb 26 '15 at 20:53
  • See http://stackoverflow.com/questions/23772801/basic-javascript-promise-implementation-attempt/23785244#23785244 , https://www.promisejs.org/implementing/ – guest271314 Feb 28 '15 at 14:41

1 Answers1

1

There's not much difference between them in how they work. The only distinction between them is that catch does not take a success and a failure callback, but only the failure callback. It can be trivially implemented as

Promise.prototype.catch = function(onFailure) {
    return this.then(null, onFailure);
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375