Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does queue.js work?

I've been trying to understand how Mike Bostock's queue.js works, but I can't see how it manages to work. The part I don't understand is how the code manages to continue executing callbacks. In particular, I am unsure about the pop() method (line 45). From my understanding, the method takes the next unprocessed, deferred function; appends a callback that (potentially) starts the next deferred function in the queue and executes when the immediately popped function finishes; then finally executes said function. My question is: what code executes this callback?

like image 403
duckworthd Avatar asked Dec 23 '12 05:12

duckworthd


People also ask

How does queue work in node JS?

A queue is a data structure used in Node. js to appropriately organize asynchronous operations. These operations exist in different forms, including HTTP requests, read or write file operations, streams, and more. Handling asynchronous operations in Node.

Does JavaScript have a queue data structure?

JavaScript Queue is one of the linear data structures used to store data in the memory. We can define a queue as a linear data structure that stores data sequentially based on the First In First Out (FIFO) manner. So, the data which is inserted first will be removed from the queue first.

Is JavaScript FIFO or LIFO?

Stacks is Last In First Out (LIFO) linear data structure. Basically, a stack of books for example, in a stack of books the last book comes first. The easiest way to use an array as a stack, using array's method push and pop.


2 Answers

Each deferred function does not actually return anything -- they are expected to execute their final argument as a callback. For example, this will not work

var foo = function(i) {
  console.log(i);
  return i;
}
var finished = function(error, results) {
  console.log(results);
}

queue(2)
  .defer(foo, 1)
  .defer(foo, 2)
  .defer(foo, 3)
  .defer(foo, 4)
  .awaitAll(finished);  // only prints "1" and "2", since foo() doesn't execute callbacks

However, if we modify foo to take a callback,

var foo = function(i, callback) {
  console.log(i);
  callback(null, i);  // first argument is error reason, second is result
}

Then it will, as executing the callback causes queue to continue.

like image 101
duckworthd Avatar answered Oct 11 '22 16:10

duckworthd


If I understand the code correctly, queue.await() and queue.awaitall() put the callback in the await instance variable, and then this is executed by notify().

like image 20
Barmar Avatar answered Oct 11 '22 16:10

Barmar