如何在node.js中使用步骤模块?

时间:2013-10-28 06:23:55

标签: node.js

我在node.js中使用step模块来获取串行执行但它没有按预期工作。

代码

   //sample
   var goalSteps = [1:{"goal":"faq","page:"faq"},2:{"goal":"offers","page:"offers"}];
   var goalConversion = [];
   var length = goalSteps.length;
    step(
              function getData() {
                var scope= this;
                for(var i =0; i < length ;i++){
                    var filter = goalSteps[i];
                     //get data from database[mongodb]
                    scope.getData(filter,function(res){
                        console.log("result",res);
                        goalConversion[i] = res;
                         if(length-1  == i){
                            this.call();
                          }
                    });
                }

              },
              function final(err, goal) {
                console.log("step2",goalConversion);
              }
        );

结果

      Step2 []

在执行 getData 功能之前,最终功能已执行。

情景 - 流动我所期待的

  1. 我想遍历goalSteps并从mongodb获取数据。

  2. 将结果推送到goalConversion数组。

  3. 根据goalSteps

  4. 获取所有数据后
  5. 在最终功能中控制goalConversion

  6. 任何帮助都会很棒。具有类似场景的步骤模块的任何示例也都很棒。

1 个答案:

答案 0 :(得分:1)

您可以使用group来运行带有动态数字的常见任务,并生成单个回调的组合结果。

var goalSteps = [1:{"goal":"faq","page:"faq"},2:{"goal":"offers","page:"offers"}];

step(
    function(){
        var scope= this;
        var group = this.group();
        for(var i =0; i < length ;i++){

            var filter = goalSteps[i];
            //get data from database[mongodb]
            scope.getData(filter, group()); // group() is how you get Step to merge multiple results into an array

         }
    },
    function final(err, goalConversion) {
            console.log("step2", goalConversion); // goalConversion is an array which contains all results
    }
);