一段 node.js 代码,如何优化防止 callback hell?

2016-07-22 14:37:49 +08:00
 allencloud
users.userExists({
        username: username
      }, function(err, exists) {
        if (err) {
          users.close();
          console.error('Error testing if user exists: ' + err);
          response.error = '业务忙,请稍候重试';
          res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
          return;
        } else if (exists) {
          users.close();
          response.error = '用户名已经存在';
          res.status(HttpStatus.CONFLICT).json(response);
          return;
        } else {
          users.emailExists(profile.email, function(err, exists) {
            console.log(profile.email +' ' + exists);
            if (err) {
              users.close();
              console.error('checking email error');
              response.error = '业务忙,请稍候重试';
              res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
              return;
            } else if (exists) {
              users.close();
              response.error = '邮箱 ' + profile.email + ' 已存在';
              res.status(HttpStatus.CONFLICT).json(response);
              return;
            }
            users.createUser(username, password, profile, function(err, uid, hash) {
              if (err) {
                response.error = '生成用户错误';
                console.error('Failed to create user ' + err);
                res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
              } else {
                response.statusMessage = '成功生成用户';
                response.uid = uid;
                // best-effort without a callback
                res.json(response);

              }
            });
          });
        }
      })
3359 次点击
所在节点    Node.js
12 条回复
zwh8800
2016-07-22 14:45:59 +08:00
用 async + await
zealic
2016-07-22 14:48:20 +08:00
你都知道 callback hell 了,为什么不知道 Promise
shiny
2016-07-22 14:50:56 +08:00
Promise 模式,还可以加点 ES2015 语法糖会更甜。
zenxds
2016-07-22 14:57:56 +08:00
Mirachael
2016-07-22 15:15:22 +08:00
挖坟贴?
plqws
2016-07-22 15:17:40 +08:00
这种程度的 hell 还好啦
按照楼主这样子的代码, async await 可能还得配合 tuple 使用…
zhuangzhuang1988
2016-07-22 15:18:26 +08:00
如果闲的蛋疼的话可以试试 http://fsprojects.github.io/Fable/
最后结果类似这样
```F#
async {
try
let! exists = users.userExists({username: username})
if exists:
res.status(HttpStatus.CONFLICT).json(response);
return;
try:
let! users.emailExists(profile.email)
if exists:
response.error = '邮箱 ' + profile.email + ' 已存在';
res.status(HttpStatus.CONFLICT).json(response);
return
try:
let! (uid, hash) = users.createUser(username, password, profile)
response.statusMessage = '成功生成用户';
response.uid = uid;
res.json(response);
except err:
response.error = '生成用户错误';
console.error('Failed to create user ' + err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);

except err:
console.error('checking email error');
response.error = '业务忙,请稍候重试';
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
except err:
console.error('Error testing if user exists: ' + err);
response.error = '业务忙,请稍候重试'
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
finally:
users.close()
}

```
zhuangzhuang1988
2016-07-22 15:18:55 +08:00
擦 , 空格都没了
hawklim
2016-07-22 16:20:39 +08:00
co 模块
DoraJDJ
2016-07-22 16:36:57 +08:00
Promise 、 Generator 、 co 、 async+await
总有一款适合你
ThinkCat
2016-07-22 17:23:55 +08:00
Promise + Generator + co 看起来优雅点,然而概念让人乱乱的
ccbikai
2016-07-23 07:40:24 +08:00
目前最合适的是 co

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/294203

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX