Простая система очереди не работает в javascript - PullRequest
1 голос
/ 14 июля 2020

В настоящее время я пытаюсь реализовать простую, но эффективную систему очередей для моего NodeJS Express API, на данный момент в моем app.get запросе есть следующее:

createOrder(req, res).catch(function ignore() {});
return res.send(functions.success_response({
    'MESSAGE': 'Order Received!'
}));

Эта функция createOrder имеет следующее:

let params = await parser.parseStringPromise(req.body.parameters);

state.device_imei = params.PARAMETERS.IMEI;

while(queue.length >= 10) {
    console.log('Current Queue Length: ' + queue.length + ', IMEI: ' + state.device_imei + ' waiting...');
}

queue.push(state.device_imei);

//some more code logic here.....

queue.splice(queue.indexOf(state.device_imei), 1 );

Моя queue переменная - это просто простая глобальная область видимости let queue = [];

Проблема, с которой я столкнулся, заключается в том, что моя очередь кажется, не уменьшается? и навсегда застрял на while()?

Кроме того, как я могу изменить while, чтобы он выполнял проверку каждую секунду, а не мгновенно повторялся?

1 Ответ

0 голосов
/ 14 июля 2020

Как упоминалось в комментариях, вы не изменяете массив queue в теле вашей while функции.

Вот рабочий пример того, чего вы хотите достичь, хотя я бы посоветовал вы изучаете альтернативы с открытым исходным кодом.

const queueState = {
  processing: false,
  items: [],
};

function processQueue() {
  if (queueState.processing) {
    return;
  }
  // Lock the queue whilst the current items are being processed
  queueState.processing = true;

  // Process items from back of queue to front
  for (let i = queueState.items.length - 1; i >= 0; i--) {
    // Do whatever you need to do with each queue item
    console.log(queueState.items[i]);
    // Remove item from queue
    queueState.items.splice(i, 1);
  }

  // Release the queue for future items to be processed
  queueState.processing = false;
}

// Start processing the queue immediately
processQueue();
// Process the queue every second (if it's not already processing)
setInterval(processQueue, 1000);

// Add some items to the queue
queueState.items.push(1);
queueState.items.push(2);
queueState.items.push(3);

// Add some more items to the queue in the future
setTimeout(() => {
  queueState.items.push(4);
  queueState.items.push(5);
}, 1500);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...