承诺从头开始

时间:2017-10-02 17:35:09

标签: javascript promise

我试图写一个小承诺实现,以了解它是如何工作的:

const MyPromise = function(executionFunction){
    this.promiseChain = [];
    this.handleError = () => {};

    this.onResolve = this.onResolve.bind(this);
    this.onReject = this.onReject.bind(this);

    executionFunction(this.onResolve, this.onReject);
};

MyPromise.prototype = {
    constructor : MyPromise,

    then(onResolve){
        this.promiseChain.push(onResolve);
        return this;
    },

    catch(handleError){
        this.handleError = handleError;
        return this;
    },

    onResolve(value){
        let storedValue = value;

        try {
            this.promiseChain.forEach(function(nextFunction){
                storedValue = nextFunction(storedValue);
            });
        }
        catch (error){
            this.promiseChain = [];
            this.onReject(error);
        }
    },

    onReject(error){
        this.handleError(error);
    }
};

我通过包装setTimeout函数测试了这个:

const delay = function(t){
    return new MyPromise(function(resolve, reject){
        setTimeout(resolve, t);
    });
};

delay(1000)
    .then(function(){
        //...
        return delay(2000);
    })
    .then(function(){
        //...
    });

您可以在此处尝试:https://jsfiddle.net/Herbertusz/1rkcfc5z/14

看起来第一个然后()运行良好,但在此之后,第二个立即启动。我该怎么做才能使then()可链接?或者我可能只是以错误的方式使用它?

0 个答案:

没有答案