我应该在使用(Bluebird)承诺的代码中完全消除try/catch吗?

Should I completely eliminate try/catch from code where I use (Bluebird) promises?

本文关键字:try catch 代码 Bluebird 承诺 我应该      更新时间:2023-09-26

在调用我承诺的函数之前,我有几个非常基本的设置步骤,我正在考虑将它们包装在try/catch块中,因为这似乎是最简单的方法。但是,我觉得有点脏。

我应该做一个函数,返回一个承诺,即使它是非常简单吗?下面是一个例子。

try
  thingyId = req.params.id # here I am 99.999% sure that params is defined,
  # but if for some bizarre reason it's not, I'd like to handle that error
  # instead of breaking the whole program
catch
  console.log "error: " + e
# do normal promisified functions

或者应该写成

setThingyId = (req) ->
  return new Promise (resolve, reject) !->
    if req.hasOwnProperty "params"
      resolve req.params.id
    else
      reject new Error "no params"
setThingyId(req)
  .then (deviceId) ->
    # other promisified functions

这个问题问得好。

  • 如果一个函数是同步的,不要返回promise,也不要在其中使用bluebird。它比同步执行慢,而且更难调试。对同步代码使用try/catch是非常合适的。当然,您可以在if中执行"params" in req,而不是使用异常,这可能更合适。

  • 如果一个函数以异步方式完成它的任务并返回一个promise,你可以使用Promise.method使它成为throw安全的

所以在你的例子中,我会写:

setThingyId = (req) ->
    if req && req.params && req.params.id
       someCalculationOverReqId req.params.id
    else 
       handleExceptionalCase req

Promise.method:

setThingyId = Promise.method (req) ->
    someCalculationOverReqId req.params.id

请注意,这只有在函数返回promise时才有意义,这样做的目的是将任何抛出转换为拒绝,从而有效地使函数抛出安全。