JavaScript类构造函数在基于承诺的方式失败时应该返回什么?

时间:2016-05-26 10:16:21

标签: javascript

我试图在构造函数中检查传递参数的值,然后以可链接的基于承诺的方式执行某些操作。但是,我发现如果我在构造函数中使用throw Error,如果失败,我不能.catch错误。我怎样才能实现这个目标?

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?

1 个答案:

答案 0 :(得分:0)

当您调用Promise.resolvePromise.reject时,这些实际上只是用于创建立即解析或拒绝的新Promise对象的辅助方法。没有理由你的错误.catch处理程序捕获 - 错误不在承诺内发生,因此它无法知道它

我建议您将错误移出构造函数并在实际检查时创建它(例如在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();
    });
  }
}