Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have read several articles on this subject, but it is still not clear to me if there is a difference between Promise.reject vs. throwing an error.(我已经阅读了几篇关于这个主题的文章,但我仍然不清楚Promise.reject与抛出错误之间是否存在差异。)

For example,(例如,) Using Promise.reject(使用Promise.reject) return asyncIsPermitted() .then(function(result) { if (result === true) { return true; } else { return Promise.reject(new PermissionDenied()); } }); Using throw(用投掷) return asyncIsPermitted() .then(function(result) { if (result === true) { return true; } else { throw new PermissionDenied(); } }); My preference is to use throw simply because it is shorter, but was wondering if there is any advantage of one over the other.(我倾向于使用throw只是因为它更短,但是想知道是否有一个优于另一个。)   ask by Naresh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
500 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is no advantage of using one vs the other, but, there is a specific case where throw won't work.(使用一个与另一个没有任何优势,但是,有一个特定的情况, throw不起作用。)

However, those cases can be fixed.(但是,这些案件可以修复。) Any time you are inside of a promise callback, you can use throw .(每当你进入promise回调时,你都可以使用throw 。) However, if you're in any other asynchronous callback, you must use reject .(但是,如果您处于任何其他异步回调中,则必须使用reject 。) For example, this won't trigger the catch:(例如,这不会触发捕获:) new Promise(function() { setTimeout(function() { throw 'or nah'; // return Promise.reject('or nah'); also won't work }, 1000); }).catch(function(e) { console.log(e); // doesn't happen }); Instead you're left with an unresolved promise and an uncaught exception.(相反,你留下了未解决的承诺和未被捕获的异常。) That is a case where you would want to instead use reject .(在这种情况下,您可能希望改为使用reject 。) However, you could fix this by promisifying the timeout:(但是,你可以通过宣告超时来解决这个问题:) function timeout(duration) { // Thanks joews return new Promise(function(resolve) { setTimeout(resolve, duration); }); } timeout(1000).then(function() { throw 'worky!'; // return Promise.reject('worky'); also works }).catch(function(e) { console.log(e); // 'worky!' });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...