【发布时间】:2016-05-08 23:29:50
【问题描述】:
当我在服务器上收到创建新游戏的发布请求时,我执行了几个查询。首先,我搜索用户是否已经在游戏中,如果是则返回游戏。否则,我会搜索一个开放的游戏,其中有人正在等待对手,如果是,则返回该游戏。最后,如果没有找到上述状态的游戏,我创建一个新游戏并将其返回。所以我的代码看起来像这样:
.post( function(req, res, next){
...findUsersExistingGame...
.then(function(game){
if(game){ return res.send(game); }
else{
return ...findUserWaitingForOpponentsGame...
}
}
.then(function(game){
if(game){ return res.send(game); }
else{
return ...createNewGame...
}
})
.then(function(game){
return res.send(game);
})
.catch(function(err){
return next(err);
});
我最终会将每个函数重构为辅助函数以提高可读性,但我需要先弄清楚链接。我的问题是,如果我在承诺链的早期发现了一个游戏(即有一个用户的现有游戏或另一个正在等待对手的用户),那么我返回 res.send(game);但是,第三个 .then 将引发错误,因为我之前的 .then() 语句返回未定义。如果我想做一个 res.send(game),如何尽早退出承诺链?
选项 1:我已经看到了抛出错误并明确捕获它的建议,但这感觉根本上是错误的,使用错误来控制流程就是这样。
选项 2:我可以做这样的事情,而不是链接承诺,但这类似于“承诺/回调地狱”:
.post( function(req, res, next){
...findUsersExistingGame...
.then(function(game){
if(game){ return res.send(game); }
else{
...findUserWaitingForOpponentsGame...
.then(function(game){
if(game){ return res.send(game); }
else{
return ...createNewGame...
.then(function(game){
return res.send(game);
});
}
})
}
}
还有其他方法吗(最好在 ES5 中,因为我仍在尝试从根本上理解 Promise,但也欢迎 ES6 回答)?
【问题讨论】:
-
听起来您正在寻找 ES7 提出的 async/await 语法 (github.com/yortus/asyncawait#1-introduction)。如果你现在想要它,你可能会为它找到一个转译器......
-
回调地狱/抛出错误是我唯一的选择吗?
-
@PDN
yield和 (ES6) 怎么样?还是event-driven architecture? -
@PDN 如果你可以使用后端,我可以给你一个很好的解决方案。
-
@stdob 你能提交一个答案吗?
标签: javascript node.js express promise es6-promise