ChanneW
V2EX  ›  问与答

怎么能把 js 的异步流程写得像同步.

  •  
  •   ChanneW · Oct 27, 2014 · 4619 views
    This topic created in 4409 days ago, the information mentioned may be changed or developed.
    看到这里有一篇文章 http://huangj.in/765 ,也想实现这样的效果. 但是我不做 nodejs , 我用在纯粹的浏览器里,有没有类似的方法.
    19 replies  •  2014-10-28 09:26:27 +08:00
    chemzqm
    chemzqm
    Oct 27, 2014
    1
    chrome可以手工开启generator,要兼容的话 promise 凑合用吧
    walkingway
    walkingway
    Oct 27, 2014❤️1
    2


    今天下午看到的
    ffffwh
    ffffwh
    Oct 27, 2014
    3
    first-class continuation?
    ttph1oc
    ttph1oc
    Oct 27, 2014
    4
    听说Q是很好的,不过我也没有真的试过。
    jybox
    jybox
    Oct 27, 2014
    5
    快上 Coffee 贼船
    ChanneW
    ChanneW
    OP
    Oct 27, 2014
    6
    $.when(
    $.ajax( "/main.php" ),
    ).then( successFunc(){
    $.when(
    $.ajax( "/333.php" ),
    ).then( Func2(){
    });
    });


    感觉 jquery 的 when - then 就是把回调函数拿到面前来了, 最终我还是会写成一大堆的嵌套, 何解?
    Mutoo
    Mutoo
    Oct 27, 2014
    7
    async.js 就挺好用。
    egen
    egen
    Oct 27, 2014 via iPhone
    8
    wind.js
    NathanInMac
    NathanInMac
    Oct 27, 2014
    9
    async.js +1

    不过没有啥完美的方案,js就这屌样
    aisk
    aisk
    Oct 27, 2014
    11
    promise
    imskull
    imskull
    Oct 27, 2014
    12
    一直用Q挺爽。
    luin
    luin
    Oct 28, 2014❤️1
    13
    @walkingway 多谢推荐!

    好巧,我这两天刚写了一个解决 JavaScript 异步的方案,是通过语法分析 + generator 实现的。可以在开发时彻底不用关心异步问题,用起来很简单,也不用 async.js 这样的异步流程控制类库。

    GitHub 上有个比较直观好懂的示例:
    https://github.com/luin/teascript

    再举个常见的例子是:

    User.findById(15, function(err, user) {
    if (user) {
    user.getProjects(function(err, projects) {
    res.json({ user: user, projects: projects });
    });
    } else {
    res.status(404).json({ error: 'not found' });
    }
    });

    可以用 TeaScript 改成:

    var user = User.findById(15, ~);
    if (user) {
    res.json({ user: user, projects: user.getProjects(~) });
    } else {
    res.status(404).json({ error: 'not found' });
    }

    目前这个项目还比较阳春,我还在抓紧完善。准备在我的下个项目中用上它,请大家多多提意见提交代码和 Star ^^

    ---

    因为 TeaScript 用了 generator,所以目前来看只能在 Node 上用。如果楼主是前端的话,还是用 Promise 和 async.js 比较好,重一点的 IcedCoffeeScript 也可以,不过不用 generator 的话确实很难有完美的方案。
    gangsta
    gangsta
    Oct 28, 2014 via iPhone
    14
    publish-subscribe pattern
    Epsil0n9
    Epsil0n9
    Oct 28, 2014
    15
    @walkingway 请问这个客户端的名字,两个旋转的箭头设计很带感
    zhyu
    zhyu
    Oct 28, 2014
    16
    Q挺好的,后来遇到了bluebird,据说性能比Q好很多(
    showhand
    showhand
    Oct 28, 2014 via Android
    17
    fibjs?
    walkingway
    walkingway
    Oct 28, 2014
    18
    @Epsil0n9 官方web呀,原生Retweet就是这样的
    wanjun
    wanjun
    Oct 28, 2014
    19
    国人开发的 fibjs,
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2140 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 14:07 · PVG 22:07 · LAX 06:07 · JFK 09:07
    ♥ Do have faith in what you're doing.