我正在寻找一种通用的模式或方法来完成以下任务:


  服务器将消息发送到(浏览器)客户端。这些消息并非全部到达,而是在不同的时间到达。
  
  对于每个传入的消息,客户端会将其与条件列表进行比较。如果消息符合条件,则满足该条件。
  
  一旦满足所有条件,客户将执行一些订单,然后移至下一组条件。
  
  重复此过程,直到满足所有可用条件集为止。


解决此问题的实际方法如下:

一组嵌套数组包含一组条件,以及满足每组条件时要执行的等效操作。例如:

var condAct =
[
  [ // set 0
    [ // conditions
      "condition 1", "condition 2"
    ],
    [ // actions
      action, action2
    ]
  ],
...


变量保留实际条件集的数量。

var condStep = 0;


消息到达时触发单个功能。它将传入消息与实际步骤中的所有条件进行比较。如果消息与条件匹配,则将条件从阵列中删除。一旦满足了此步骤的所有条件,并从数组中删除了所有条件,便会执行操作,然后转到下一步:

function condRcv(msg){
  for (var i = 0; i < condAct[condStep][0].length; i++) { // for each condition in the actual set
    if(msg === condAct[condStep][0][i]){ // if it matches the incoming message
      condAct[condStep][0].splice(i, 1); // remove the condition from the array
      if(condAct[condStep][0].length === 0){ // and if the actual conditions array is already empty
        for(var j = 0; j < condAct[condStep][1].length; j++){ // for each action in the actions array
          condAct[condStep][1][j]; // execute it
          condStep++; // up a step
          return; // get outta here
        }
      }
    }
  }
}


我的方法最初似乎是有效的,但过程和代码都有些复杂。

js甚至jquery中是否有一种常用的模式或方法来解决这种情况?

谢谢。
如果您认为我可以改善这个问题,请告诉我。

最佳答案

您可以使用.queue().promise().then()



var q = $({});

var queueName = "conditions";

var arr = [1,2,4,4,5];

var conditions = [2,3,4,5,7];

var results = [];

var fn = function (prop, next) {
  console.log(prop);
  results.push(prop);
  next();
}

q.queue(queueName, $.map(arr, function(curr, index) {
  return function(next) {
    return curr + 1 === conditions[index]
           ? fn(curr + 1 + " equals " + conditions[index], next)
           : /* do other stuff here, pass `next` function, call `next` */
             fn("curr plus 1 does not equal " + conditions[index], next)
  }
}));

var promise = q.dequeue(queueName).promise(queueName);

promise
.then(function() {
  console.log("complete", results);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

10-04 16:14
查看更多