如何在Angular中实现Promise中的错误链

时间:2018-07-30 05:58:41

标签: angular ionic-framework promise

我当前正在编写一个Ionic应用程序,需要链接错误,但是不知何故我一直在得到它

ERROR Error: Uncaught (in promise): [object Object]

当我尝试拒绝该错误时。我想我一定在某处做错了事,但我不知道该怎么做。该错误只能通过doSomething()方法处理。

代码的结构如下:

sendRequest(...) {
    ...
    return new Promise(resolve => {
      this.http.post(this.server, body, {headers: header, withCredentials: true}).subscribe(data => {
        resolve(data);
      }, err => {
        return Promise.reject(err);
      });
    });
  }

procesRequest(...) {
    ...
    return new Promise(resolve => {
      this.sendRequest(...).then((data) => {
        resolve(data);
      }, (reason) => {
        return Promise.reject(reason);
      }).catch((error => {
        return Promise.reject(error);
      }));
    });
  }

doSomething {
    ...
    processRequest(...).then((data) => {
      this.showSuccessMessage();
    }, (err) => {
      this.showErrorMessage(err);
    }).catch((err) => {
      this.showErrorMessage(err);
    });
}

1 个答案:

答案 0 :(得分:1)

基本示例如下:

var promise1 = new Promise(function(resolve, reject) {
    var cleanRoom = false;
  	if(!cleanRoom){
    	reject('promise1 rejected');
    }
});
var promise2 = new Promise(function(resolve, reject) {
  	if(true){
    	reject('promise2 rejected');
    }
});
function doSomething () {
	promise1.catch((rej) => {
    	console.log(rej);
    });
  	promise2.catch((rej) => {
    	console.log(rej);
    });
}
doSomething();