在离子页面中返回Promise.reject

时间:2016-08-23 13:35:54

标签: javascript angular es6-promise

我正在从组件内部调用一个服务方法,它返回一个Promise。如果承诺得到解决或拒绝,我想做不同的事情。我是这样做的:

调用服务方法的函数

onAddProvider() {
  this.userInteraction.addContact(data.email, 'bp').then(
    successMessage => {
      doSomething();
    },
    failureMessage => {
      doSomethingElse();
    });
}

服务方法

addContact(email: string, type: string) {
  return new Promise((resolve, reject) => {
    if (!email.match(patterns.email)) {
      return Promise.reject('Bad email address');
    }

    let data = {
      to: email,
      from: this.dataStorage.data.id,
      type: type,
      date: new Date().getTime()
    };

    this.http.post(`${serverURL}action=sendAddRequest&token=${localStorage['token']}`, JSON.stringify(data))
      .map((res: Response) => res.text())
      .subscribe(response => {
        resolve('Request sent');
      });
  });
}

我希望在返回Promise.reject时运行failureMessage函数,但我在控制台中收到此错误:

EXCEPTION: Error: Uncaught (in promise): Bad email address

2 个答案:

答案 0 :(得分:1)

替换:

return Promise.reject('Bad email address');

return reject('Bad email address');

答案 1 :(得分:0)

也可以拒绝抛出错误。

throw "Error";