subqueue.js 920 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. var _ = require('lodash');
  3. module.exports = SubQueue;
  4. function SubQueue() {
  5. this.__queue__ = [];
  6. }
  7. /**
  8. * Add a task to this queue
  9. * @param {Function} task
  10. */
  11. SubQueue.prototype.push = function( task, opt ) {
  12. opt = opt || {};
  13. // Don't register named task if they're already planned
  14. if ( opt.once && _.find(this.__queue__, { name: opt.once }) ) {
  15. return;
  16. }
  17. this.__queue__.push({ task: task, name: opt.once });
  18. };
  19. /**
  20. * Return the first entry of this queue
  21. * @return {Function} The first task
  22. */
  23. SubQueue.prototype.shift = function() {
  24. return this.__queue__.shift();
  25. };
  26. /**
  27. * Run task
  28. * @param {Function} skip Callback if no task is available
  29. * @param {Function} done Callback once the task is completed
  30. */
  31. SubQueue.prototype.run = function( skip, done ) {
  32. if ( this.__queue__.length === 0 ) return skip();
  33. setImmediate( this.shift().task.bind(null, done) );
  34. };