原生js实现promise部分功能

Emitter 工具函数

function Emitter() {

}

Emitter.prototype.on = function(evtype, fn) {
  this._events = this._events || {};
  this._events[evtype] = this._events[evtype] || [];
  if (this._events[evtype].indexOf(fn) !== -1) return;
  this._events[evtype].push(fn);
}
Emitter.prototype.off = function(evtype, fn) {
  this._events = this._events || {};
  if (evtype in this._events === false)  return;
  fn && this._events[evtype].splice(this._events[evtype].indexOf(fn), 1);
  !fn && delete this._events[evtype];
}
Emitter.prototype.emit = function(evtype, detail) {
  this._events = this._events || {};
  var self = this;
  if (evtype in this._events === false) return;
  this._events[evtype].forEach(function(fn, i) {
      fn.call(self, detail);
  });
}

Emitter.eventify = function(Klass) {
    Klass.prototype = Object.create(Klass.prototype);
    for (var attr in Emitter.prototype) {
        Klass.prototype[attr] = Emitter.prototype[attr]
    }
    return Klass;
}

Promise函数

var MyPromise = function(executor) {
    var self = this;
    function resolve(value) {
        self.emit('RESOLVED', value); // 观察者模式(解耦)
    }
    setTimeout(function() {
        executor(resolve);
    }, 0);
}

MyPromise.prototype.then = function(onResolved) {
    var self = this;
    var p2 = new MyPromise(function(resolve) {});

    //注册事件
    this.on('RESOLVED', function(value) {
        var ret = onResolved(value);
                if (ret instanceof MyPromise) {
                  ret.then(function(ret) {
                    p2.emit('RESOLVED', ret);
                  });
                }
                else {
                  p2.emit('RESOLVED', ret); //触发事件
                }
        
    });

    return p2;
}

Emitter.eventify(MyPromise);

DEMO

var p1 = new MyPromise(function (resolve) {
    resolve(42);
});
var p2 = p1.then(function (value) {
    console.log(value)
  return value + 2;
});

var p3 = p2.then(function (value) {
  console.log(value);
}); 

你可能感兴趣的:(原生js实现promise部分功能)