es5实现简单 Promise ,手动实现 简单 Promise



function MyPromise(callback) {
    this.subs = [];
    // 这里的 resolve 和 reject 需要手动绑定 this ,
    //要不然,resolve函数只是一个函数,
    //绑定不到当前 MyPromise 的实例
    callback(this.resolve.bind(this), this.reject.bind(this))
}
MyPromise.prototype.resolve = function (data) {
    if (this.subs && this.subs.length) {
        this.subs.shift()(data)
    }else{
        if(this.finalyFn){
            this.finalyFn('resolved')
        }
    }
}

MyPromise.prototype.reject = function (data) {
    this.subs = [];
    if(this.finalyFn){
        this.finalyFn('rejected')
    }
}
MyPromise.prototype.then = function (fn) {
    this.subs.push(fn);
    // 这里,需要 return this ,保证当前调用者仍是 当前的 MyPromise 实例
    return this;
}
MyPromise.prototype.finaly = function (fn) {
    this.finalyFn = fn
}
var a = new MyPromise(function (resolve, reject) {
    setTimeout(function () {
        console.log('resolve')
        resolve(1)
    }, 1250)
})
a.then(function (data) {
    setTimeout(function () {
        console.log(data)
        a.resolve('then---1')
    }, 2000)
}).then(function (data) {
    setTimeout(function () {
        console.log(data)
        a.reject('reject')
    }, 1000)
}).then(function (data) {
    setTimeout(function () {
        console.log(data)
    }, 1000)
})



 

你可能感兴趣的:(JavaScript,ES6)