node.js async类库的使用

最近玩儿node.js很上瘾。在用redis的时候遇到了一个问题。

node中所有的操作都是异步的,这就带来了一些个问题:我要等所有的查询都执行完以后才能够render页面。我问了csser的同学。他给我推荐了async类库,我研究了一下,完全可以解决现在的问题。

----------------

安装:npm install async

类库的主页: https://github.com/caolan/async#queue 上面有大量的例程。

 

目前我用了一个同步,贴上来大家一览

   async.series([

  function(callback){

      client.get("string key",function(err,reply){

      pig = reply;

      console.log("change pig to " + reply);

      console.log("now pig is " + pig);

      client.quit();

      callback(null,1);

  });

  

  },

  function(callback){

   console.log("beginRender: " + pig);

   res.render('index', { title:pig });

   callback(null,2);

  }

  ]);

一------------

这个的语法上相对繁琐,有一个step类库貌似也不错。

 async.series([
  function(callback){
      client.get("string key",function(err,reply){
      pig = reply;
      console.log("change pig to " + reply);
      console.log("now pig is " + pig);
      client.quit();
      callback(null,1);
  });
  
  },
  function(callback){
   console.log("beginRender: " + pig);
   res.render('index', { title:pig });
   callback(null,2);
  }

posted on 2012-06-15 13:40  亭子  阅读(690)  评论(0编辑  收藏  举报

导航