Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于Promise异常 #12

Open
39Er opened this issue May 16, 2017 · 0 comments
Open

关于Promise异常 #12

39Er opened this issue May 16, 2017 · 0 comments

Comments

@39Er
Copy link
Owner

39Er commented May 16, 2017

Promise异常有两种捕获方式:一种是就近捕获,还有一种是最后catch()统一捕获。

Promise.resolve()
  .then( () => {
    // 使 .then() 返回一个 rejected promise
    throw 'Oh no!';
  })
  .then( () => {
    console.log( 'Not called.' );
  }, reason => {
    console.error( 'onRejected function called: ', reason );
});

只会捕获第一个then()中的异常,如第二个then()中抛出异常不会捕获。
优点:可以灵活处理每一个error;
缺点:如果有未捕获的异常,会报错: UnhandledPromiseRejectionWarning

Promise.resolve()
  .then( () => {
    // 使 .then() 返回一个 rejected promise
    throw 'Oh no!';
  })
  .then( () => {
    console.log( 'Not called.' );
  })
  .catch((reason) =>{
	console.error('onRejected function called: ', reason);
  });

catch()会捕获前面所有then()中抛出的异常。
优点:不会出现没有捕获的异常;
缺点: 进行个性化处理时会很复杂

建议:灵活混用这两种方法,需要特别处理时就近处理,不关注的error放在最后统一捕获处理。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant