我正在寻找一种通用的模式或方法来完成以下任务:
A server sends messages to a (browser) client. These messages do NOT arrive alltogether, but in different moments in time.
For each incoming message the client compares it with a list of conditions. If message matches condition, that condition is satisfied.
Once all conditions are satisfied, the client executes some orders, and moves to the next set of conditions.
This is repeated until all sets of conditions available are satisfied.
我解决这个问题的实际方法如下:
一组嵌套数组包含条件集,以及满足每组条件时要执行的等效操作。例如:
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>
关于javascript - 在执行之前,在不同时刻清除几个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40009761/