원생 js 프로미스 부분 기능 실현

2112 단어

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);
}); 

좋은 웹페이지 즐겨찾기