Answer the question
In order to leave comments, you need to log in
Why such strange behavior in JS?
Hello. I will try to briefly describe the problem. There is a class:
class RedisAPI {
constructor(redis) {
this.masterID = new Array(); //здесь хранятся уникальные ID всех воркеров
this.master = redis.createClient();
}
addWorker(id) {
this.masterID.push(id);
console.log(`Worker ${id} is working!`);
}
//отправление сообщения на обработку одному из воркеру
emit() {
let needID = this.masterID.splice(0, 1);
console.log(`arr: ${this.masterID.length}; first: ${needID[0]}`);
this.masterID.push(needID[0]);
}
//отправление сообщения на обработку одному из воркеров каждые ms секунд
emitTimeout(ms) {
setInterval(() => {
this.emit();
}, ms);
}
}
const queue = new RedisAPI(redis);
queue.emitTimeout(1000);
Answer the question
In order to leave comments, you need to log in
//отправление сообщения на обработку одному из воркеру
emit() {
let length = this.masterID.length;
let needID = this.masterID.splice(0, 1);
console.log(`arr: ${length}; first: ${needID[0]}`);
this.masterID.push(needID[0]);
}
Why is this all?
let needID = this.masterID.splice(0, 1);
...
this.masterID.push(needID[0]);
class RedisAPI {
constructor() {
this.masterID = new Array(); //здесь хранятся уникальные ID всех воркеров
}
addWorker(id) {
this.masterID.push(id);
console.log(`Worker ${id} is working!`);
}
//отправление сообщения на обработку одному из воркеру
emit() {
if (this.masterID.length) {
let needID = this.masterID.splice(0, 1);
console.log(`arr: ${this.masterID.length}; first: ${needID[0]}`);
this.masterID.push(needID[0]);
} else {
console.log('The queue is empty!');
}
}
//отправление сообщения на обработку одному из воркеров каждые ms секунд
emitTimeout(ms) {
setInterval(() => {
this.emit();
}, ms);
}
}
var queue = new RedisAPI();
queue.emitTimeout(1000);
setTimeout(function() {
queue.addWorker(42);
}, 1500);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question