V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
allencloud
V2EX  ›  Node.js

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

  •  
  •   allencloud · 2016-07-22 14:37:49 +08:00 · 3345 次点击
    这是一个创建于 2835 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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);
    
                  }
                });
              });
            }
          })
    
    12 条回复    2016-07-23 07:40:24 +08:00
    zwh8800
        1
    zwh8800  
       2016-07-22 14:45:59 +08:00
    用 async + await
    zealic
        2
    zealic  
       2016-07-22 14:48:20 +08:00
    你都知道 callback hell 了,为什么不知道 Promise
    shiny
        3
    shiny  
       2016-07-22 14:50:56 +08:00
    Promise 模式,还可以加点 ES2015 语法糖会更甜。
    zenxds
        4
    zenxds  
       2016-07-22 14:57:56 +08:00
    Mirachael
        5
    Mirachael  
       2016-07-22 15:15:22 +08:00
    挖坟贴?
    plqws
        6
    plqws  
       2016-07-22 15:17:40 +08:00
    这种程度的 hell 还好啦
    按照楼主这样子的代码, async await 可能还得配合 tuple 使用…
    zhuangzhuang1988
        7
    zhuangzhuang1988  
       2016-07-22 15:18:26 +08:00   ❤️ 1
    如果闲的蛋疼的话可以试试 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
        8
    zhuangzhuang1988  
       2016-07-22 15:18:55 +08:00
    擦 , 空格都没了
    hawklim
        9
    hawklim  
       2016-07-22 16:20:39 +08:00
    co 模块
    DoraJDJ
        10
    DoraJDJ  
       2016-07-22 16:36:57 +08:00 via Android
    Promise 、 Generator 、 co 、 async+await
    总有一款适合你
    ThinkCat
        11
    ThinkCat  
       2016-07-22 17:23:55 +08:00
    Promise + Generator + co 看起来优雅点,然而概念让人乱乱的
    ccbikai
        12
    ccbikai  
       2016-07-23 07:40:24 +08:00 via iPhone
    目前最合适的是 co
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2848 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 15:01 · PVG 23:01 · LAX 08:01 · JFK 11:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.