You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.1 KiB

  1. /*
  2. var q = Queue();
  3. q(id, function (next) {
  4. // whatever you need to do....
  5. // when you're done
  6. next(); // guaranteed to be asynchronous :D
  7. });
  8. */
  9. var fix1 = function (f, x) {
  10. return function () { f(x); };
  11. };
  12. module.exports = function () {
  13. var map = {};
  14. var next = function (id) {
  15. setTimeout(function () {
  16. if (map[id] && map[id].length === 0) { return void delete map[id]; }
  17. var task = map[id].shift();
  18. task(fix1(next, id));
  19. });
  20. };
  21. return function (id, task) {
  22. // support initialization with just a function
  23. if (typeof(id) === 'function' && typeof(task) === 'undefined') {
  24. task = id;
  25. id = '';
  26. }
  27. // ...but you really need to pass a function
  28. if (typeof(task) !== 'function') { throw new Error("Expected function"); }
  29. // if the intended queue already has tasks in progress, add this one to the end of the queue
  30. if (map[id]) { return void map[id].push(task); }
  31. // otherwise create a queue containing the given task
  32. map[id] = [task];
  33. next(id);
  34. };
  35. };