无法确定如何有选择地处理承诺链中的错误......
我不确定何时应该返回一个新的promise(使用new,或promise.reject或promise.fulfill),如何打破链(返回promise.reject或throw?),以及哪个拒绝是被.done捕获 - 以及如何只处理.done中的一些错误?
(本地化会很好,即避免使用全局变量,就像之前我在回调地狱中那样。另外,除非共同处理,否则请将错误处理放在原因附近。)
上下文:" / save"的快速路由处理程序具有一些复杂的逻辑,并且可选地是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建议反而接受内在的承诺?
答案 0 :(得分:0)
女。我最终抛出/拒绝打破链,并依赖于完成/捕获明确地接收异常/拒绝值以区分未处理的“异常”: http://decodecode.net/elitist/2014/12/levelup-promises-promises/
显然,目前还没有更好的控制流程结构?