1

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?

Herbertusz
  • 1,151
  • 1
  • 11
  • 19
  • 3
    Maybe not related to the problem, but `.then` and `.catch` should return *new* promises, not the same promise. – Felix Kling Oct 02 '17 at 17:46
  • Take a look at the spec (https://promisesaplus.com/). As @FelixKling mentioned, you have to return a new promise which is either fulfilled or rejected using the return value of the function. – Razem Oct 02 '17 at 17:55
  • @FelixKling That's quite definitely *the* problem. A promise chain is formed by having multiple promises depending on each other, not a single object having an array of callbacks. – Bergi Oct 02 '17 at 18:13
  • Maybe [this](https://stackoverflow.com/a/24980140/1048572) helps – Bergi Oct 02 '17 at 18:16
  • @Bergi Then I think the entire way I tried this was wrong. I find your implementation here: https://stackoverflow.com/questions/15668075/concept-distilling-how-a-promise-works/15668353#15668353 I investigate this now, thanks. – Herbertusz Oct 02 '17 at 19:00
  • there are [dozens of implementations](https://promisesaplus.com/implementations) - check out some of the "simpler" ones (100 to 300 lines of code) – Jaromanda X Oct 02 '17 at 21:35

0 Answers0