Monday, 29 May 2017

Using Promises inside class method

I'm creating this es6 class to organize documents in folders, and the class has one method that should be used by the user: go, example:

const options = {
 // options here.
};
const organizer = Organizer("path/to/folder", options);

// example
organizer.go().then(() => {

}).catch(console.error);

And inside the go method, i'm using Promises to control the flow of what i need to do:

class Organizer {
  constructor(path, options) {
    this.path = path;
    this.options = options;
  }


  go() {
    Promise.resolve(getListOfFiles())
      .then(doSomethingOne)
      .then(doSomethingTwo)
      .then(etc)
  }

  getListOfFiles() {
    // use this.path to get list of files and return in a Promise way (resolve, reject)
    return new Promise((resolve, reject) => {
    });
  }

  doSomethingOne(files) {
    // something sync
    return .....;
  }

  doSomethingTwo(files) {
    // something async
    return new Promise((resolve, reject) => {
      // ....
    });
  }

  etc() {
  }
}

And i would like to know if I'm doing wrong by using Promises to control the execution flow, i never really program using the OOP paradigm, i always used function, but in this case the options will be needed in several places.

Thank you.



via FXux

No comments:

Post a Comment