最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reject a promise from then() - Stack Overflow

programmeradmin4浏览0评论

How can you reject a promise from inside its then()?

For example:

Promise.all(promiseArr).then(()=>{
  if(cond){
    //reject
  }
}).catch(()=>{ /*do something*/ });

The only relevant question I found was this: How to reject a promise from inside then function but it's from 2014, so there must be a better way then to throw by now with support of ES6.

How can you reject a promise from inside its then()?

For example:

Promise.all(promiseArr).then(()=>{
  if(cond){
    //reject
  }
}).catch(()=>{ /*do something*/ });

The only relevant question I found was this: How to reject a promise from inside then function but it's from 2014, so there must be a better way then to throw by now with support of ES6.

Share Improve this question edited May 23, 2017 at 10:30 CommunityBot 11 silver badge asked Apr 9, 2017 at 12:21 shinzoushinzou 6,22215 gold badges73 silver badges137 bronze badges 4
  • 1 A rejected promise is just the async way to describe an Error – Thomas Commented Apr 9, 2017 at 12:28
  • Does it matter what I throw? @Thomas – shinzou Commented Apr 9, 2017 at 12:34
  • 2 ideally, something that describes the error that happened any you'll want to show in your console if unhandled. – Thomas Commented Apr 9, 2017 at 12:37
  • 2 throwing is still perfectly valid in ES6. You could also return Promise.reject() if throw feels unnatural. – CodingIntrigue Commented Apr 9, 2017 at 12:45
Add a ment  | 

2 Answers 2

Reset to default 11

ES6/ES2015 is still JavaScript and doesn't offer anything new regarding promise rejection. In fact, native promises are ES6.

It is either

promise
.then(() => {
  return Promise.reject(...);
})
.catch(...);

or

promise
.then(() => {
  throw ...;
})
.catch(...);

And throw is more idiomatic (and generally more performant) way to do this.

This may not be true for other promise implementations. E.g. in AngularJS throw and $q.reject() is not the same thing.

I have found out (after hours of scratching my head) that if a throw is within an async method such as setTimeout(() => throw new Error('description')) it will be treated as an Unhandled Exception and will NOT end up in your .catch() block (you'll only see it in the console window) - see this article where I found out about that difference between throw and Promise.reject.

发布评论

评论列表(0)

  1. 暂无评论