寻找在nodejs应用程序中管理异步流的主流方法

时间:2012-09-02 04:12:03

标签: node.js workflow

我有这个简单的nodejs应用程序,它为我的Web应用程序生成虚拟日期。 它所做的就是:

  1. 删除虚拟数据库
  2. 填充广告资源集
  3. 填充发票集合
  4. 填充const数据集合
  5. 当然,所有操作都是异步的,我想一个接一个地顺序执行它们。对我来说,编写一些东西来管理这种流程更简单,但是,我想要一个主流解决方案,它将支持其他类型的流程。例如,并行运行并在第一次失败时停止所有操作。

    请参考下面的骨架,以供您参考,描述我的解决方案:

    /*global require, console, process*/
    
    var mongo, db, inventory, createChain;
    
    function generateInventory(count) {
      // returns the generated inventory
    }
    
    function generateInvoices(count, inventory) {
      // returns the generated invoices
    }
    
    function generateConst() {
      // returns the generated const data
    }
    
    mongo = require('mongojs');
    db = mongo.connect('dummy', ['invoices', 'const', 'inventory']);
    
    createChain = function () {
      "use strict";
      var chain = [false], i = 0;
    
      return {
        add: function (action, errMsg, resultCallback) {
          chain[chain.length - 1] = {action: action, errMsg: errMsg, resultCallback: resultCallback};
          chain.push(false);
          return this;
        },
        invoke: function (exit) {
          var str, that = this;
          if (chain[i]) {
            chain[i].action(function (err, o) {
              if (err || !o) {
                str = chain[i].errMsg;
                if (err && err.message) {
                  str = str + ": " + err.message;
                }
                console.log(str);
              } else {
                if (chain[i].resultCallback) {
                  chain[i].resultCallback(o);
                }
                i += 1;
                that.invoke(exit);
              }
            });
          } else {
            console.log("done.");
            if (exit) {
              process.exit();
            }
          }
        }
      };
    };
    
    createChain()
      .add(function (callback) {
        "use strict";
        console.log("Dropping the dummy database.");
        db.dropDatabase(callback);
      }, "Failed to drop the dummy database")
      .add(function (callback) {
        "use strict";
        console.log("Populating the inventory.");
        db.inventory.insert(generateInventory(100), callback);
      }, "Failed to populate the inventory collection", function (res) {
        "use strict";
        inventory = res;
      })
      .add(function (callback) {
        "use strict";
        console.log("Populating the invoices.");
        db.invoices.insert(generateInvoices(10, inventory), callback);
      }, "Failed to populate the invoices collection")
      .add(function (callback) {
        "use strict";
        console.log("Populating the const.");
        db["const"].insert(generateConst(), callback);
      }, "Failed to populate the const collection")
      .invoke(true);
    

    任何人都可以建议一个相关的nodejs包,它也很容易使用吗?

    非常感谢。

2 个答案:

答案 0 :(得分:2)

使用async模块提供您可能需要的任何类型的流量控制。特别是,series方法提供顺序流控制。

答案 1 :(得分:0)

实际上,对于顺序流控制,您应该使用瀑布

举个例子:

async.waterfall([
  function(cb){
    cb(null,1);
  },
  function(r,cb){
    // r=1
    cb(null,2)
  },
  function(r,cb){
    // r=2
    cb(null,3)
  }
],function(e,r){
    // e=null
    // r=3
})

这将按顺序执行。 如果你提前回调一个错误(即cb(“error”)),那么它将直接转到最终函数(e,r),e =“error”并且r = undefined 注意函数(r,cb){}如何在util库中预先组合以处理常用的重用块,并使将来的事情变得更容易。