JavaScript承诺 - 拒绝与抛出 [英] JavaScript Promises - reject vs. throw

查看:85
本文介绍了JavaScript承诺 - 拒绝与抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几篇关于这个主题的文章,但我仍然不清楚 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();
        }
    });

我的偏好是使用抛出只是因为它更短,但想知道是否有任何一个优势。

My preference is to use throw simply because it is shorter, but was wondering if there is any advantage of one over the other.

推荐答案

使用一个没有优势vs另一个,但是,有一个特定的情况, 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.

任何时候你都在一个承诺回调中,你可以使用 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.

例如,

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 。但是,你可以通过宣告超时来解决这个问题:

won't trigger the catch, 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 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!'
});

这篇关于JavaScript承诺 - 拒绝与抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆