JavaScript Promises - 拒绝与抛出 [英] JavaScript Promises - reject vs. throw
问题描述
我已经阅读了几篇关于这个主题的文章,但我仍然不清楚 Promise.reject
与抛出错误之间是否有区别.例如,
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. For example,
使用 Promise.reject
return asyncIsPermitted()
.then(function(result) {
if (result === true) {
return true;
}
else {
return Promise.reject(new PermissionDenied());
}
});
使用投掷
return asyncIsPermitted()
.then(function(result) {
if (result === true) {
return true;
}
else {
throw new PermissionDenied();
}
});
我更喜欢使用 throw
只是因为它更短,但想知道一个比另一个有什么优势.
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
不起作用.但是,这些情况是可以修复的.
There is no advantage of using one vs the other, but, there is a specific case where throw
won't work. However, those cases can be fixed.
任何时候在 promise 回调中,都可以使用 throw
.但是,如果您在任何其他异步回调中,则必须使用 reject
.
Any time you are inside of a promise callback, you can use throw
. However, if you're in any other asynchronous callback, you must use 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
});
取而代之的是一个未解决的承诺和一个未捕获的异常.在这种情况下,您可能希望改用 reject
.但是,您可以通过两种方式解决此问题.
Instead you're left with an unresolved promise and an uncaught exception. That is a case where you would want to instead use reject
. However, you could fix this in two ways.
- 通过在超时内使用原始 Promise 的拒绝函数:
new Promise(function(resolve, reject) {
setTimeout(function() {
reject('or nah');
}, 1000);
}).catch(function(e) {
console.log(e); // works!
});
- 通过承诺超时:
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!'
});
这篇关于JavaScript Promises - 拒绝与抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!