3

Upon writing code in es6 following a tutorial, I get error -

class APromise {
  constructor(fn) {
    this.state = 'pending';
    this.value = null;
    this.deferred = undefined;
    fn(this.resolve);
  }

  resolve(newValue) {
    this.value = newValue;    // ERROR HERE
    this.state = 'resolved';
    if (this.deferred) {
      this.handle(this.deferred);
    }
  }

  handle(onResolved) {
    if (this.state == 'pending') {
      this.deferred = onResolved;
    } else {
      onResolved(this.value);
    }
  }

  then(onResolved) {
    this.handle(onResolved);
  }
}

const log = v => {
  console.log(v);
};
const myFun = () => {
  return new APromise(resolve => {
    resolve('Hello World');
  });
};

myFun().then(log);

Error -

this.value = newValue;
           ^
TypeError: Cannot set property 'value' of undefined

But I'm already inside my es6 class, why is it saying this to be undefined? I tried debugging and looking for same problem in google but I can't find a similar one :(

1 Answers1

2

When you pass this.resolve to fn, you need to bind it to the APromise instance:

fn(this.resolve.bind(this));

Demo:

class APromise {
  constructor(fn) {
    this.state = 'pending';
    this.value = null;
    this.deferred = undefined;
    fn(this.resolve.bind(this));
  }

  resolve(newValue) {
    this.value = newValue; // ERROR HERE
    this.state = 'resolved';
    if (this.deferred) {
      this.handle(this.deferred);
    }
  }

  handle(onResolved) {
    if (this.state == 'pending') {
      this.deferred = onResolved;
    } else {
      onResolved(this.value);
    }
  }

  then(onResolved) {
    this.handle(onResolved);
  }
}

const log = v => {
  console.log(v);
};
const myFun = () => {
  return new APromise(resolve => {
    resolve('Hello World');
  });
};

myFun().then(log);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209