简体   繁体   中英

What should JavaScript class constructor return when it fails in promise-based way?

I'm trying to check value of passing parameters in constructor, then do something in a chainable promise-based way. However, I found if I use throw Error in constructor if it fails, I cannot .catch the error. How can I achieve this goal?

class Car {
  constructor(name = '', brand = '') {
    if (!name || !brand) {
      throw new Error('Initiate error');
    }
    this.name = name;
    this.brand = brand;
  }

  beep() {
    return Promise.resolve(`${this.brand}-${this.name}`);
  }
}

const audi = new Car('A8', 'Audi');
audi.beep()
  .then((val) => console.log(val))

const test = new Car();
test.beep()
  .then((val) => console.log(val))
  .catch((error) => console.log(error)); // This line didn't work, how can I get the error thrown by constructor?

When you call Promise.resolve or Promise.reject , these are effectively just helper methods for creating a new Promise object that immediately resolves or rejects. There's no reason your error should get caught by the .catch handler - the error doesn't take place within the promise, so it has no way of knowing about it.

I'd recommend moving your error out of the constructor and create it when it's actually being checked (ie in beep ):

class Car {
  constructor(name = '', brand = '') {
    this.name = name;
    this.brand = brand;
  }

  beep() {
    return new Promise(function (resolve, reject) {
      if (!this.name || !this.brand) {
        reject(new Error('Initiate error'));
      }

      resolve();
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM