我也來扔一個Promise吧……

sasa-m發表於2019-07-26
function res(pre) {
    let resFn, rejFn, fns = this.fns;
    while (!resFn && fns.length > 0) {
        [resFn, rejFn] = fns.shift();
    }
    if (resFn && pre && pre.status === "pending") {
        return pre.then((ret) => exec.call(this, resFn, ret), (ret) => rej.call(this, rejFn, ret));
    }
    resFn ? exec.call(this, resFn, pre) : this.status = "resolved";
}


function rej(pre,fn) {
    while (!fn && fns.length > 0) {
        fn = fns.shift()[1];
    }
    fn ? exec.call(this, fn, pre) : this.status = "rejected";
}

function exec(fn, pre) {
    this.value = pre;
    try {
        res.call(this, fn(pre));
    } catch (e) {
        rej.call(this, e);
    }
}


function Promise(fn) {
    this.status = "pending";
    this.fns=[];
    setTimeout(() => fn((ret) => res.call(this, ret), (ret) => rej.call(this, ret)));
    return this;
}
Promise.prototype.then=function (resFn, rejFn) {
    let status = this.status;
    if (status !== "pending") {
        exec.call(this, status === "resolved" ? resFn : rejFn, this.value);
    } else {
        this.fns.push([resFn,rejFn]);
    }
    return this;
};
Promise.prototype.catch=function(fn){
    this.then(undefined,fn);
};
複製程式碼

其它的api給留給大佬了……

相關文章