I've tried to write a little promise implementation to understand how it works under the hood:
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);
    }
};
I tested this by wrapping the setTimeout function:
const delay = function(t){
    return new MyPromise(function(resolve, reject){
        setTimeout(resolve, t);
    });
};
delay(1000)
    .then(function(){
        //...
        return delay(2000);
    })
    .then(function(){
        //...
    });
You can try here: https://jsfiddle.net/Herbertusz/1rkcfc5z/14
It looks like the first then() works well, but after this, the second start immediately. What should I do to make the then() chainable? Or maybe I just use it in a wrong way?
