手写promise

15 阅读1分钟


function MyPromise(exector) {
    let _this = this
    _this.status = 'pending';
    _this.value = null;
    _this.reason = null;
    _this.onResolvedCallBacks = []
    _this.onRejectedCallBacks = []

    function resolve(v) {
        if (_this.status == 'pending') {
            _this.value = v
            _this.status = 'resolve'
            _this.onResolvedCallBacks.forEach(cb => cb())
        }
    }
    function reject(e) {
        if (_this.status == 'pending') {
            _this.reason = e
            _this.status = 'reject'
            _this.onRejectedCallBacks.forEach(cb => cb())
        }
    }

    try {
        exector(resolve, reject)
    } catch (e) {
        reject(e)
    }
}


MyPromise.prototype.myThen = function (onResolved, onRejected) {
    let _this = this
    const nmp = new MyPromise((resolve, reject) => {
        if (_this.status == 'resolve') {
            const x = onResolved(_this.value)
            resolve(x)
        }
        if (_this.status == 'reject') {
            const x = onRejected(_this.reason)
            reject(x)
        }
        if (_this.status == 'pending') {
            _this.onResolvedCallBacks.push(() => {
                const x = onResolved(_this.value)
                resolve(x)
            })
            _this.onRejectedCallBacks.push(() => {
                const x = onRejected(_this.reason)
                reject(x)
            })
        }
    })

    return nmp
}


let mp = new MyPromise(
    (resolve, reject) => {
        setTimeout(() => {
            //resolve('哈哈哈')
            reject('123')
        }, 1000)
    }
)

mp.myThen(
    res => { console.log('================res', res) },
    err => { console.log('================err', err) }
    )