一段 node.js 代码,如何优化防止 callback hell? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
allencloud
V2EX    Node.js

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

  •  
  •   allencloud 2016-07-22 14:37:49 +08:00 3927 次点击
    这是一个创建于 3441 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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  
    PRO
       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  
    PRO
       2016-07-23 07:40:24 +08:00 via iPhone
    目前最合适的是 co
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     3731 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 38ms UTC 00:52 PVG 08:52 LAX 16:52 JFK 19:52
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86