如何从作为每当功能被添加到其队列中的数组执行的功能?
我有一双匹配算法,我添加一个函数调用以充当队列阵列,并且通过一个执行一个以避免冲突时匹配。我想要的东西,以保持和眼睛上的队列,当功能被添加到队列中执行。就像一个常规检查,如果数组有任何元素?我能做到这一点使用类似resque
库?
编辑:让我做我的问题清楚。我使用socket.io
其中i 2个用户搭配在一起,并分享了一些数据和他们的用户点击按钮对和对函数调用有一个游戏。但问题是,在高峰时间用户A获得匹配B和B获取与C.匹配这不应该发生。所以我排队配对函数调用使用和数组。我想阵列执行每个函数调用了一个又一个。将有次当阵列将是很长一段时间队列为空。
希望这简单的代码来排队与参数和上下文的功能,以后执行它们可以满足您的问题...
/**
* Wrapping function code
*
* fn - reference to function
* context - "this" context
* params - array of parameters to pass to the function
*/
var wrapFun = function(fn, context, params) {
return function() {
fn.apply(context, params);
};
}
// the function to be wrapped
var pairMatch = function(userA, userB) {
// your matching code here...
console.log('matching user', userA.name, 'with user', userB.name);
}
var user1 = { name: 'Alice' };
var user2 = { name: 'Bob' };
var user3 = { name: 'Charlie' };
var userN = { name: 'Zoe' };
// wrap the function (the parameters must be in an array)
var fun1 = wrapFun(pairMatch, this, [user1, user2]);
var fun2 = wrapFun(pairMatch, this, [user3, userN]);
// create an array and append your wrapped functions to it
var funQ = [];
funQ.push(fun1);
funQ.push(fun2);
// shift all items (functions) in the array, and execute one by one...
while (funQ.length) {
(funQ.shift())();
}