简体   繁体   中英

node.js for loop parallel array processing with only one callback

i want to make a for loop with a pattern-array and one object to check if the object is matched by one pattern. The patterns-array should processed parallel and if one of the patterns matches the object the onMatch()-callback-function should be called and cancel the other operations else the onNoMatch()-function should be called.

At the Moment it looks like this. I dont know where to put the onNoMatch()-function and sometimes there are multiple callbacks:

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);
        }
    }
}

//EDIT working solution

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()');
});

I would personally prefer using async library as these sort of workflows can be easily handled using 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM