1

I have the following code.

var queue = require('async').queue(function(task, callback) {
  console.log("QUEUED JOB STARTED");
  require('sleep').sleep(10);
  console.log("QUEUED JOB FINISHED");
  callback();
}, 1);

router.post('/generate/', function(request, result) {
  console.log("REQUEST RECEIVED");
  queue.push({});
  result.end();
  console.log("REQUEST PROCESSED");
});

When the first request comes it is immediately processed. But when the next comes just after the first one, the server waits until the queued job is finished (10 seconds) so the output is:

REQUEST RECEIVED
REQUEST PROCESSED
QUEUED JOB STARTED
QUEUED JOB FINISHED
REQUEST RECEIVED
REQUEST PROCESSED
QUEUED JOB STARTED
QUEUED JOB FINISHED

Is it possible to make Node.js enqueue and answer the second request without waiting for the first to achieve the following output?

REQUEST RECEIVED
REQUEST PROCESSED
REQUEST RECEIVED
REQUEST PROCESSED
QUEUED JOB STARTED
QUEUED JOB FINISHED
QUEUED JOB STARTED
QUEUED JOB FINISHED
nkdm
  • 1,220
  • 1
  • 11
  • 26
  • It's single threaded, whenever you call `sleep`, it's going to sleep and not handle more requests, as that's what `sleep()` does, it uses a while loop to block the entire thread. – adeneo Jan 20 '15 at 10:07
  • So what is the point of using async.queue if it is single threaded? – nkdm Jan 20 '15 at 10:18
  • Asynchronous and multithreaded is not the same thing, when you block the thread, you block the thread, and that's what `sleep` does. – adeneo Jan 20 '15 at 10:20
  • If you wan't async behaviour, use a promise or timeout – adeneo Jan 20 '15 at 10:21
  • I want to have a job queue and have some control of it (read how many tasks are waiting, how many are processed at the moment etc.) – nkdm Jan 20 '15 at 10:23
  • There's an answer here that creates a queue system -> http://stackoverflow.com/questions/20967006/how-to-create-a-sleep-delay-in-nodejs-that-is-blocking – adeneo Jan 20 '15 at 11:18

0 Answers0