Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Promise within Class

Fun with promises today … I’m trying to figure out why I can’t refer to this.promise to resolve it with another method, it’s always null.

Any enlightenment is appreciated 🙂

export default class Example {
  constructor() {
    this.promise = null
  }

  test() {
    this.promise = new Promise((resolve, reject) => {
      this.something()
    }).then(resolve => {
      // resolved, do something else
    }).catch(reject => {
      console.log('reject', reject)
    })
  }

  something() {
    this.promise.resolve()
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re trying to use this.promise in something before it’s value changes from null. Another way to do this is to pass the resolve as an argument:

class Example {
  constructor() {
    this.promise = null;
  }
  test() {
    this.promise = new Promise((resolve, reject) => {
      this.something(resolve);
    }).then(result => {
      console.log('resolve', result);
    }).catch(error => {
      console.log('reject', error);
    });
  }
  something(resolve) {
    resolve(1);
  }
}
const example = new Example();
example.test();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading