简体   繁体   English

等待Promise.reject或抛出错误来拯救?

[英]await Promise.reject or throw error to bail out?

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 ) 这样做的原因之一是我想要一个catch块来处理所有错误情况(如此处所述, 了解node.js中的promise promise

My question is when I hit a sync error, should I call await Promise.reject or throw error to bail out the process? 我的问题是,当我遇到同步错误时,我应该调用await Promise.reject还是throw error来挽救这个过程? I know either way will work but I prefer throw error . 我知道无论哪种方式都有效,但我更喜欢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. 使用throw来立即终止控制流似乎是一个更好的选择。

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. 我不是在谈论诺言链(我的问题的全部要点),所以我不认为线程JavaScript承诺 - 拒绝与抛出回答了我的问题。

I read the article Error Handling in Node.js I don't think it gives an answer either. 我读过Node.js中的文章错误处理我不认为它给出了答案。 But it did say 但确实如此

A given function should deliver operational errors either synchronously (with throw) or asynchronously (with a callback or event emitter), but not both . 给定的函数应该同步(使用throw)或异步(使用回调或事件发射器)传递操作错误, 但不能同时传递两者 ... In general, using throw and expecting a caller to use try/catch is pretty rare... ...一般来说,使用throw并期望调用者使用try / catch是非常罕见的...

My async function(s) may return Promise.reject. 我的异步函数可能会返回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) {
  ...
}

It's semantically correct to use throw in promise control flow, this is generally preferable way to bail out of promise chain. 使用throw in promise控制流在语义上是正确的,这通常是摆脱承诺链的最佳方式。

Depending on coding style, await Promise.reject(...) may be used to differentiate between real errors and expected rejections. 根据编码风格, await Promise.reject(...)可用于区分真实错误和预期拒绝。 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. 带有字符串原因的拒绝承诺有效,但throw 'invalid result'被认为是可以使用linter规则解决的样式问题,因为将常规使用Error实例作为例外。

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. 之所以重要,是因为使用instanceof Error无法检测到字符串异常,并且没有message属性,因为console.warn(error.message)一致错误记录将导致模糊的undefined条目。

// 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: 由于invalid result实际上是一个错误,因此将其设为一个是合理的:

  throw new TypeError('invalid result');

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. 我不是在谈论诺言链(我的问题的全部要点),所以我不认为线程JavaScript承诺 - 拒绝与抛出回答了我的问题。

async function is syntactic sugar for promise chain, so all points that are applicable to promises are applicable to async as well. async函数是promise链的语法糖,因此适用于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. 可能存在抛出错误与拒绝承诺不同的情况,但它们特定于其他承诺实现,如AngularJS $q并且不会影响ES6承诺。 Synchronous error in Promise constructor results in exception, this also isn't applicable to async . Promise构造函数中的同步错误导致异常,这也不适用于async

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM