异步 API 应该同步抛出吗? [英] Should an async API ever throw synchronously?

查看:22
本文介绍了异步 API 应该同步抛出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 JavaScript 函数,它发出 HTTP 请求并返回结果的承诺(但这个问题同样适用于基于回调的实现).

I'm writing a JavaScript function that makes an HTTP request and returns a promise for the result (but this question applies equally for a callback-based implementation).

如果我立即知道为函数提供的参数无效,函数应该 throw 同步,还是应该返回一个被拒绝的承诺(或者,如果你愿意,用 错误实例)?

If I know immediately that the arguments supplied for the function are invalid, should the function throw synchronously, or should it return a rejected promise (or, if you prefer, invoke callback with an Error instance)?

异步函数应该总是以异步方式运行有多重要,特别是对于错误情况?如果您知道程序处于不适合进行异步操作的状态,是否可以throw?

How important is it that an async function should always behave in an async manner, particularly for error conditions? Is it OK to throw if you know that the program is not in a suitable state for the async operation to proceed?

例如:

function getUserById(userId, cb) {
  if (userId !== parseInt(userId)) {
    throw new Error('userId is not valid')
  }

  // make async call
}

// OR...

function getUserById(userId, cb) {
  if (userId !== parseInt(userId)) {
    return cb(new Error('userId is not valid'))
  }

  // make async call
}

推荐答案

最终是否同步抛出的决定取决于你,你很可能会发现有人争论任何一方.重要的是记录行为并保持行为的一致性.

Ultimately the decision to synchronously throw or not is up to you, and you will likely find people who argue either side. The important thing is to document the behavior and maintain consistency in the behavior.

我对这个问题的意见是你的第二个选择——将错误传递给回调——看起来更优雅.否则,您最终会得到如下所示的代码:

My opinion on the matter is that your second option - passing the error into the callback - seems more elegant. Otherwise you end up with code that looks like this:

try {
    getUserById(7, function (response) {
       if (response.isSuccess) {
           //Success case
       } else {
           //Failure case
       }
    });
} catch (error) {
    //Other failure case
}

这里的控制流程有点混乱.

The control flow here is slightly confusing.

在回调中使用单个 if/else if/else 结构并放弃周围的 try/catch 似乎会更好.

It seems like it would be better to have a single if / else if / else structure in the callback and forgo the surrounding try / catch.

这篇关于异步 API 应该同步抛出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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