【问题标题】:How to selectively handle async errors in promise chain?如何有选择地处理承诺链中的异步错误?
【发布时间】:2015-01-27 20:21:45
【问题描述】:

不知道如何选择性地处理承诺链中的错误...

我不确定何时应该返回一个新的 Promise(使用 new、promise.reject 或 Promise.fulfill),如何打破链条(返回 Promise.reject 或 throw?),以及哪个拒绝被捕获.done — 以及如何只处理 .done 中的一些错误?

(本地化会很好,即避免全局变量,就像我之前在回调地狱中所做的那样。此外,除非集体处理,否则请保持错误处理接近原因。)

上下文:“/save”的快速路由处理程序,逻辑有些复杂,并且可以选择promisified LevelDB。

promise=require 'promise' # (Capitalize Promise in anticipation of ES6?)
db=(require 'level-promise') sub (require 'level') './data',keyEncoding:'utf8',valueEncoding:'json'

简化的未经测试的伪代码(显然是CoffeeScript),例如:

.post '/save',(req,res)->
    new promise ->
        # Validations… Sync stuff.
        unless req.body.role then return promise.reject res.send 400,'Missing role.'
        # Etc.
        promise.fulfill()
    .then ->
        # Permissions, similarly, but 403...

    .then ->
        # But what about async stuff?
        # If changing username, ensure availability.
        return new promise (fulfill,reject)->
            if key_change
                db.get r.username,(err,v)-> # Why not promisified/denodeify?!
                    unless err?.notFound then reject res.send 400,'Username already taken.' # Throw instead?
                    else
                        changes.push type:'del',key:r.current_username
                        fulfill() # ?
            else fulfill() # ?
            # Or .catch here?

    # .catch here?
    .then ->
        # Etc.
    .then ->return db.batch changes # Promisified?

    # Error handling for everything (that wasn't already).
    .done ->res.send 200,'Saved.'
    ,-> # Which rejection caught here?
        res.send 500,'Oops...'

    # Or better?
    .then ->res.send 200,'Saved.'
    .catch -> # Which rejection caught here?
        res.send 500,'Oops...'
    .done() # Because catch doesn't end chain?

谢谢!

PS:http://www.html5rocks.com/en/tutorials/es6/promises/ 看起来很有帮助,但我还没有消化。似乎建议我需要在链中添加 .catch'es?但How to stop/break in the middle of chained promises 建议改为抓住内心的承诺?

【问题讨论】:

  • stackoverflow.com/questions/26076511/… 似乎回答了这个问题,但使用 Bluebird 而不是 promise 模块,所以我不确定……
  • 承诺模块:promisejs.org
  • 我的答案同样适合这里,您可以使用它。此外,您应该考虑不使用 promise 模块并改用 Bluebird - 它更快,并且提供更好的堆栈跟踪。

标签: express coffeescript promise


【解决方案1】:

努。我最终抛出/拒绝来破坏链条,并依赖完成/捕获明确接收异常/拒绝值来区分未处理的“异常”: http://decodecode.net/elitist/2014/12/levelup-promises-promises/

显然,还没有更好的控制流结构吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2017-01-22
    • 2018-11-07
    • 2020-03-22
    • 2019-02-21
    • 2019-09-25
    相关资源
    最近更新 更多