简体   繁体   English

承诺:拒绝的一些问题

[英]Promises: some problems with reject

I have an issue with promise in 'Angular 2'. 我对“ Angular 2”中的承诺有疑问。

Please see my code below: 请在下面查看我的代码:

getPromise1().then((result) => { 
        console.log("promise1 result"); 
    }, (error) => { 
        console.log("promise1 error"); 
    });

function getPromise1() {
    return getPromise2().then((result) => {
        console.log("promise2 result");
    }, (error) => {
        console.log("promise2 error");
    });

}

function getPromise2() {
    return new Promise((resolve, reject) => {
        reject("error");
    });
}

And the result is: promise2 error and promise1 result . 结果是: promise2 errorpromise1 result
I don't know why not promise2 error and promise1 error 我不知道为什么不promise2 errorpromise1 error
Any problem and the solution for this case? 有什么问题和解决方案吗?
This is preview link: http://plnkr.co/edit/RTc1wYfO8e1YPUrXM6GN 这是预览链接: http : //plnkr.co/edit/RTc1wYfO8e1YPUrXM6GN

When a promise rejects, the control jumps to the closest rejection handler down the chain . 当一个Promise拒绝时, 控件将跳至最接近的拒绝处理程序

so, Here the .catch block finishes normally. 因此, .catch块在此处正常完成。 So the next successful handler is called. 因此,将调用下一个成功的处理程序。 Or it could return something, that would be the same. 否则它可能会返回某些结果,那就一样。

Hence the result 因此结果

And the result is: promise2 error and promise1 result . 结果是: promise2 errorpromise1 result

So you could have as many .then as we want, and then use a single .catch at the end to handle errors in all of them. 因此,您可以根据需要设置多个.then,然后最后使用单个.catch来处理所有错误。

But to get the following result 但是要得到以下结果

I don't know why not promise2 error and promise1 error 我不知道为什么不promise2 errorpromise1 error

you need to re-throw the error 您需要重新抛出错误

throw error;

And here the .catch block analyzes the error and throws it again: .catch块在这里分析错误并再次抛出该错误:

function getPromise1() {
    return getPromise2().then((result) => {
        console.log("promise2 result");
    }, (error) => {
        console.log("promise2 error");
        throw error;
    });

}

If you handle a rejection in any promise chain then that's going to make the resulting chain to be fulfilled until an error is found then it goes back to being rejected. 如果您处理任何承诺链中的拒绝,那么这将使结果链得到满足,直到发现错误,然后它才被拒绝。 Think about it in terms of sync code, would you have expected this to print error A and error B ? 考虑一下同步代码,您是否期望它会显示error Aerror B

function myFnA(){
    throw new Error('A is bad');
}

function myFnB(){
   try {
      myFnA();
      console.log('good A');
   } catch(e){
      console.log('error A');
   }
}

function myFnC(){
   try {
      myFnB();
      console.log('good B');
   }
   catch(e){
      console.log('error B');
   }
}

myFnC();

myFnB fixes myFnA error. myFnB修复了myFnA错误。 So myFnB is doing it's job right. 因此, myFnB的工作做对了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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