简体   繁体   中英

Return Promise.reject in ionic page

I'm calling a service method from inside a component, which returns me a Promise. I want to do different things based on if the promise is resolved or rejected. I'm doing it like this:

the function that calls the service method

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

the service method

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');
      });
  });
}

I was expecting the failureMessage function to run when Promise.reject is returned, but instead I get this error in the console:

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

Replace:

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

with

return reject('Bad email address');

也可以拒绝它并引发错误。

throw "Error";

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