等待Promise.reject或抛出错误来拯救? [英] await Promise.reject or throw error to bail out?

查看:698
本文介绍了等待Promise.reject或抛出错误来拯救?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构我的承诺,将代码链接到异步/等待样式。这样做的原因之一是我想要一个catch块来处理所有错误情况(如下所述了解node.js中的promise拒绝

I am refactoring my promise chaining codes to async/await style. One of the reasons to do that is I want a single catch block to handle to all error situations (as explained here Understanding promise rejection in node.js)

我的问题是当我遇到同步错误时,我应该调用 await Promise.reject 抛出错误来拯救这个过程?
我知道两种方式都可以,但我更喜欢抛出错误。我已经知道我得到了无效的结果我为什么要等待?使用throw来立即终止控制流似乎是一个更好的选择。

My question is when I hit a sync error, should I call await Promise.reject or throw error to bail out the process? I know either way will work but I prefer throw error. I already know I got an invalid result why should I await? Using throw to terminate the control flow immediately seems to be a better option.

我不是在谈论诺言链(我的问题的全部意义),所以我不喜欢我认为线程 JavaScript承诺 - 拒绝投掷回答了我的问题。

I am not talking about the promise chain(the whole point of my question), so I don't think the thread JavaScript Promises - reject vs. throw answered my question.

我读过文章 Node.js中的错误处理我认为它也没有给出答案。但它确实说

I read the article Error Handling in Node.js I don't think it gives an answer either. But it did say


给定的函数应该同步(带抛出)
或异步(带回调或事件
发射器),但不是两者。 ...一般来说,使用throw和期望
a来电者使用try / catch是非常罕见的...

A given function should deliver operational errors either synchronously (with throw) or asynchronously (with a callback or event emitter), but not both. ... In general, using throw and expecting a caller to use try/catch is pretty rare...

My异步函数可能会返回Promise.reject。所以我担心引入两种方式来提供错误,因为该文章反对。

My async function(s) may return Promise.reject. So I am concerned about introducing 2 ways to delivering errors as that article against.

try {
   let result = await aysncFunc().
   if (!isResultValid(result)) { //isResultValid() is sync function 
      await Promise.reject('invalid result')
      //or throw 'invalid result'
   }
   ... //further processing
}
catch (error) {
  ...
}


推荐答案

在promise控件中使用 throw 在语义上是正确的流,这通常是摆脱承诺链的好方法。

It's semantically correct to use throw in promise control flow, this is generally preferable way to bail out of promise chain.

根据编码风格,等待Promise.reject(...)可用于区分真实错误和预期拒绝。字符串原因的拒绝承诺有效,但抛出'无效结果'被认为是样式问题,可以通过 linter rules ,因为通常使用 Error 实例作为例外。

Depending on coding style, await Promise.reject(...) may be used to differentiate between real errors and expected rejections. Rejected promise with string reason is valid but throw 'invalid result' is considered style problem that may be addressed with linter rules, because it's conventional to use Error instances as exceptions.

之所以重要,是因为 instanceof Error 无法检测到字符串异常,并且没有消息属性,一致的错误记录为 console.warn(error.message)将导致模糊未定义条目。

The reason why it's important is because string exceptions can't be detected with instanceof Error and don't have message property, consistent error logging as console.warn(error.message) will result in obscure undefined entries.

// ok
class Success extends Error {}
try {
  throw new Success('just a friendly notification');
} catch (err) {
  if (!(err instanceof Success)) {
    console.warn(err.message);
    throw err;
  }
}

// more or less
const SUCCESS = 'just a friendly notification';
try {
  await Promise.reject(SUCCESS);
} catch (err) {
  if (err !== SUCCESS)) {
    console.warn(err.message);
    throw err;
  }
}

// not ok
try {
  throw 'exception';
} catch (err) {
  if (typeof err === 'string') {
    console.warn(err);
  } else {
    console.warn(err.message);
  }

  throw err;
}

由于结果无效实际上是一个错误,让它成为一个是合理的:

Since invalid result is actually an error, it's reasonable to make it one:

  throw new TypeError('invalid result');




我不是在谈论诺言链(我的全部观点)问题),所以我不认为线程JavaScript承诺 - 拒绝与抛出回答了我的问题。

I am not talking about the promise chain(the whole point of my question), so I don't think the thread JavaScript Promises - reject vs. throw answered my question.

async 函数是promise链的语法糖,所以所有的点都是适用于承诺也适用于 async

async function is syntactic sugar for promise chain, so all points that are applicable to promises are applicable to async as well.

可能存在抛出错误的情况不同拒绝承诺,但它们特定于其他承诺实施,如AngularJS $ q ,并且不影响ES6承诺。 Promise 构造函数中的同步错误导致异常,这也不适用于 async

There may be cases when throwing an error is not the same as rejecting a promise, but they are specific to other promise implementations like AngularJS $q and don't affect ES6 promises. Synchronous error in Promise constructor results in exception, this also isn't applicable to async.

这篇关于等待Promise.reject或抛出错误来拯救?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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