MyPromise.prototype.then = function (onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function'? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function'? onRejected : reason => { throw reason };
    return new MyPromise((resolve, reject) => {
        if (this.state === 'fulfilled') {
            setTimeout(() => {
                try {
                    const x = onFulfilled(this.value);
                    resolvePromise(resolve, reject, x);
                } catch (error) {
                    reject(error);
                }
            });
        }
        if (this.state ==='rejected') {
            setTimeout(() => {
                try {
                    const x = onRejected(this.reason);
                    resolvePromise(resolve, reject, x);
                } catch (error) {
                    reject(error);
                }
            });
        }
        if (this.state === 'pending') {
            this.resolveCallbacks.push(() => {
                setTimeout(() => {
                    try {
                        const x = onFulfilled(this.value);
                        resolvePromise(resolve, reject, x);
                    } catch (error) {
                        reject(error);
                    }
                });
            });
            this.rejectCallbacks.push(() => {
                setTimeout(() => {
                    try {
                        const x = onRejected(this.reason);
                        resolvePromise(resolve, reject, x);
                    } catch (error) {
                        reject(error);
                    }
                });
            });
        }
    });
};