我正在尝试在节点js中实现一个队列。我有一个包含元素的数组,我希望每1秒插入一个新的。我想每次只返回队列中的两个元素(每5秒一次)我希望队列继续从遗留的地方返回值。例如。我有一个数组[1,2,3,4]
。每2秒我在数组中插入一个新元素。我每5秒从数组中返回2个元素。有谁知道如何使这项工作?这是我的代码:
var queue = require('queue');
var posts=["aaa","bbbb","ccc",'ddd'];
var n=posts.length;
function populateQueue(q) {
for (var i = 0; i < posts.length; i++) {
(function(index) {
q.push(function(done) {
console.log('done', posts[index]);
setTimeout(done, 5000);
posts.splice(0,2);
});
})(i);
}
}
function insert() {
posts.push({"name":haiku()});
cxc();
}
function cxc() {
populateQueue(q2);
}
setInterval(insert,2000);
var q2 = queue({concurrency: 2});
populateQueue(q2);
q2.start();
function haiku(){
var adjs = ["autumn", "hidden", "bitter", "misty", "silent", "empty", "dry",
"dark", "summer", "icy", "delicate", "quiet", "white", "cool", "spring",
"winter", "patient", "twilight", "dawn", "crimson", "wispy", "weathered",
"blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green",
"long", "late", "lingering", "bold", "little", "morning", "muddy", "old",
"red", "rough", "still", "small", "sparkling", "throbbing", "shy",
"wandering", "withered", "wild", "black", "young", "holy", "solitary",
"fragrant", "aged", "snowy", "proud", "floral", "restless", "divine",
"polished", "ancient", "purple", "lively", "nameless"]
, nouns = ["waterfall", "river", "breeze", "moon", "rain", "wind", "sea",
"morning", "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn",
"glitter", "forest", "hill", "cloud", "meadow", "sun", "glade", "bird",
"brook", "butterfly", "bush", "dew", "dust", "field", "fire", "flower",
"firefly", "feather", "grass", "haze", "mountain", "night", "pond",
"darkness", "snowflake", "silence", "sound", "sky", "shape", "surf",
"thunder", "violet", "water", "wildflower", "wave", "water", "resonance",
"sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper",
"frog", "smoke", "star"];
return adjs[Math.floor(Math.random()*(adjs.length-1))]+"_"+nouns[Math.floor(Math.random()*(nouns.length-1))];
}
答案 0 :(得分:0)
我快速回答这个问题。特别涉及您的问题,但不涉及您的代码。你必须告诉我你的代码是做什么的,否则我无法帮助你。但是关于你的问题,我有这个:
首先,设置初始队列和索引。
let queue = [1, 2, 3, 4, 5],
index = 0;
现在你必须声明两个函数,(1)在数组中排列值的函数。就我而言,我将一个随机数排队
enqueue = () => {
queue.push(Math.floor(Math.random()*10));
console.log(queue);
}
另一个在当前索引处获取两个值,并在存储完成后将索引递增2。然后返回值。
get_two_elements = () => {
let pointed_slice = queue.slice(index, index + 2);
index += 2;
console.log(pointed_slice);
return pointed_slice;
};
最后,为了让装置工作,你必须像这样对它们施加超时
setInterval(enqueue, 2000);
setInterval(get_two_elements, 5000);
设置间隔是非阻塞的,因此两者都将在几乎相同的时间发生,差异在纳秒和毫秒之间。这将成功地完成您的问题听起来对我的意见。
作为参考,我在这里为您提供了整个代码的要点: