How does queue.js work?

2019-06-22 07:54发布

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?

2条回答
Animai°情兽
2楼-- · 2019-06-22 08:33

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.

查看更多
在下西门庆
3楼-- · 2019-06-22 08:42

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().

查看更多
登录 后发表回答