模拟ES6 Promise的轻量级实现

  • Post author:
  • Post category:其他


Promise是ES6提供的原生的异步编程解决方案,它的出现主要是为了解决回调地狱实现异步编程的糟糕语法。最早是由社区提出并实现的。本文提供了一个轻量级的Promise实现方式,主要想解释下Promise实现的主要原理。至于更细节的部分,本文不做阐述。

我已经将该轻量级的Promise实现放到了Gist上面:


https://gist.github.com/licaomeng/528d0a63c3305531c5b36c138fea17dc

function MyPromise(fn) {
    this.resolve;
    this.reject;
    _this = this;
    setTimeout(function () {
        fn(_this.resolveFunc.bind(_this), _this.rejectFunc.bind(_this));
    }, 0)
}

MyPromise.prototype = {
    then: function (resolve, reject) {
        this.resolve = resolve;
        this.reject = reject;
    },
    resolveFunc: function (value) {
        this.resolve(value);
    },
    rejectFunc: function (value) {
        this.reject(value);
    }
}


new MyPromise(function (resolve, reject) {
    var flag = Math.round(Math.random())
    if (flag) {
        r



版权声明:本文为licaomengRICE原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。