node.js用于循环并行数组处理,只有一个回调

时间:2015-09-23 10:46:24

标签: javascript arrays node.js parallel-processing

我想用一个模式数组和一个对象创建一个for循环,以检查该对象是否与一个模式匹配。 patterns-array应该并行处理,如果其中一个模式与对象匹配,则应调用onMatch() - callback-function并取消其他操作,否则应调用onNoMatch()函数。

在片刻,它看起来像这样。我不知道在哪里放置onNoMatch() - 函数,有时会有多个回调:

module.exports = function matchingPattern(patterns, object, onMatch, onNoMatch) {
    for (key in patterns) {
        if(patterns[key].param1 != object.param1) continue;
        else if(patterns[key].param2 != object.param2) continue;
        else if(patterns[key].param3 != object.param3) continue;
        else {
            onMatch(patterns[key].id);
        }
    }
}

//编辑工作解决方案

var arr = [1,2,3,4,5]
var async = require('async');

function matchPattern(pat, object, cb){
    console.log(pat +' % '+ object);
    if(pat % object == 0) cb(pat); 
    else cb();
}

function matchingPattern(patterns, object, onMatch, onNoMatch) {
    async.each(patterns, function(pat, callback){
        matchPattern(pat, object, function(match){
            return callback(match);
        });
    }, function (res){
        if(res) return onMatch(res);
        return onNoMatch()
    });
}

matchingPattern(arr, {2=2matches, 6=no matches}, function onMath(a){
    console.log('onMatch('+a+')');
}, function onNoMatch(){
    console.log('onNoMatch()');
});

1 个答案:

答案 0 :(得分:0)

我个人更喜欢使用异步库,因为使用async可以轻松处理这些工作流程。

var FOUND = {
  code: 'Custom'
  item: null,
  pattern: null
};

  function matchingPattern(patterns, object, onMatch, onNoMatch) {  
    async.each(patterns, function(pattern, callback){
      // check pattern as per your business logic.
    // assuming matchPattern is async
       matchPattern(pattern, object, function(match){
           if(match){
             FOUND.item = object;
             FOUND.pattern = pattern;
             return callback(FOUND);
           }else{
             return callback();
           }
       }); 
    },
    function (error, result){
      if(error){
        if(error.code == 'Custom'){
          // its not an error. We have used it as an error only.
          return onMatch();
        }else{
          // handle error here.
        }
      }
      // all items done and we have not found any pattern matching.
      return onNoMatch();
    });// end of async.each();
}// end of matchingPattern()