0

I tried to implement custom promise implementation using plain vanilla JavaScript. But its not working for async then function. How do I make async chaining in my code?

Here is my code:

var noop = () => { };

function Promise(callback) {
  callback = callback || noop;
  var thenCallbacks = [];

  this.promisedValue = null;

  this.then = function (callback) {
    callback = callback || noop;
    thenCallbacks.push(callback);
    //this.promisedValue = callback(this.promisedValue) || this.promisedValue;
    return this;
  }

  this.done = function () {
    if (!thenCallbacks.length) {
      debugger;
      return this.promisedValue;
    } else {
      for (var i = 0; i < thenCallbacks.length; i++) {
        this.promisedValue = thenCallbacks[i].call(this, this.promisedValue);
      }
    }
    debugger;
    return this.promisedValue;
  }
  var res = (d) => {
    this.promisedValue = d;
  }

  var rej = (d) => {
    this.promisedValue = d;
  }

  callback.call(this, res, rej);
};

var p = new Promise((res, rej) => {
  res(100);
}).then((d) => {
  console.log('Then 1 called!! ', d);
  return 100233;
}).done();
  • *"I tried to implement custom promise implementation using plain vanilla JavaScript"* Why? When promises are built in, and for obsolete environments where they aren't, there are high-quality, well-tested libraries to do it? If it's for learning purposes, it's probably worth studying some of the existing libs as a starting point. – T.J. Crowder Nov 08 '17 at 12:14
  • 2
    Also note that this implementation breaks one of the key features of promises as defined by the [Promises/A+ spec](https://promisesaplus.com/). `then` shouldn't just add a callback. It should add a callback and create a *new* promise that will be resolved with the return value of that callback (or slaved to that value, if it's a thenable). – T.J. Crowder Nov 08 '17 at 12:17
  • 1
    *"But its not working for async then function"* What async `then` function? I don't see anything async above at all (which is another issue; `then` and `catch` callbacks must *always* be called asynchronously). – T.J. Crowder Nov 08 '17 at 12:17
  • 2
    it would be impressive to implement Promise/A+ compliant promise in 35 lines of code - took me 197 lines (though I do have Promise.all and Promise.race and Promise.resolve and Promise.reject implemented as well) - so i guess I did it in 137 lines – Jaromanda X Nov 08 '17 at 12:30
  • 2
    You will want to have a look at [this very simple example](https://stackoverflow.com/a/15668353/1048572) (or [this one, with error handling](https://stackoverflow.com/a/17724387/1048572)) – Bergi Nov 08 '17 at 13:58
  • 1
    @JaromandaX There are some *really* small ones in the [implementations lists](https://promisesaplus.com/implementations) :-) – Bergi Nov 08 '17 at 14:02

0 Answers0