0

我在 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. goalConversion在最终功能中控制台。

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

4

1 回答 1

1

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

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
    }
);
于 2013-10-28T10:17:09.290 回答