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?
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.
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.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With