// 手写promise
function newPromise(callback) {
    this.state = 'pending';
    this.successArray = [];
    this.failArray = [];
    // this.res
    // 成功时候的回调函数
    let resolve = data => {
        // 改变状态
        this.state = 'fulfilled';
        // 储存数据
        this.res = data;
        // 遍历回调函数执行
        this.successArray.forEach(fn => this.res = fn(this.res))
        // 清空回调函数
        this.successArray = [];
    }
    // 失败时候的回调函数
    let reject = data => {
        this.state = 'rejected';
        this.res = data;
        this.failArray.forEach(fn =>  this.res = fn(this.res))
        this.failArray = [];
    }
    try {
        callback(resolve, reject) 
    }catch(e) {
        reject(e)
    }
}
newPromise.prototype.then = function(success, fail) {
        if(this.state === 'pending'){
            success && this.successArray.push(success)
            fail && this.fail.push(fail);
        }else if(this.state === 'fulfiiied') {
            success && success(this.res)
        }else {
            fail && fail(this.res)
        }
 }