如果一个异步API不断抛出同步? [英] Should an async API ever throw synchronously?

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

问题描述

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

如果我立即,对于函数提供的参数是无效的,应功能罚球同步,还是应该返回一个拒绝承诺(或者,如果你$ P知道$ PFER,与错误实例)调用回调?

如何重要的是它是一个异步函数应该的总是的行为以异步的方式,特别是对错误条件?是否确定罚球如果你知道程序是不是在合适的状态异步操作继续进行?

例如:

 函数getUserById(用户ID,CB){
  如果(用户ID!== parseInt函数(用户ID)){
    抛出新的错误('标识无效')
  }  //使异步调用
}// 要么...功能getUserById(用户标识,CB){
  如果(用户ID!== parseInt函数(用户ID)){
    返回CB(新的错误('标识无效'))
  }  //使异步调用
}


解决方案

最终决定抛出同步与否是你的,你很可能会发现谁认为任何一方的人。最重要的是记录的行为和保持行为的一致性。

我的的意见的对此事的是你的第二个方案 - 传递错误进入回调 - 看起来更优雅。否则,你最终与code,看起来像这样:

  {尝试
    getUserById(7,功能(响应){
       如果(response.isSuccess){
           //成功案例
       }其他{
           //失败案例
       }
    });
}赶上(错误){
    //其它故障情况
}

这里的控制流程略显混乱。

看起来这将是更好的有一个的if / else,如果在回调/其他结构和放弃周围的的try / catch

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).

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)?

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?

e.g:

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.

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天全站免登陆