queue.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. function Queue (n) {
  2. n = parseInt(n || 1, 10);
  3. return (n && n > 0) ? new Queue.prototype.init(n) : null;
  4. }
  5. Queue.prototype = {
  6. init: function (n) {
  7. this.threads = [];
  8. this.taskList = [];
  9. while (n--) {
  10. this.threads.push(new this.Thread)
  11. }
  12. },
  13. /**
  14. * @callback {Fucntion} promise对象done时的回调函数,它的返回值必须是一个promise对象
  15. */
  16. push: function (callback) {
  17. if (typeof callback !== 'function') return;
  18. var index = this.indexOfIdle();
  19. if (index != -1) {
  20. this.threads[index].idle(callback)
  21. try { console.log('Thread-' + (index+1) + ' accept the task!') } catch (e) {}
  22. }
  23. else {
  24. this.taskList.push(callback);
  25. for (var i = 0, l = this.threads.length; i < l; i++) {
  26. (function(thread, self, id){
  27. thread.idle(function(){
  28. if (self.taskList.length > 0) {
  29. try { console.log('Thread-' + (id+1) + ' accept the task!') } catch (e) {}
  30. var promise = self.taskList.pop()(); // 正确的返回值应该是一个promise对象
  31. return promise.promise ? promise : thread.promise;
  32. } else {
  33. return thread.promise
  34. }
  35. })
  36. })(this.threads[i], this, i);
  37. }
  38. }
  39. },
  40. indexOfIdle: function () {
  41. var threads = this.threads,
  42. thread = null,
  43. index = -1;
  44. for (var i = 0, l = threads.length; i < l; i++) {
  45. thread = threads[i];
  46. if (thread.promise.state() === 'resolved') {
  47. index = i;
  48. break;
  49. }
  50. }
  51. return index;
  52. },
  53. Thread: function () {
  54. this.promise = $.Deferred().resolve().promise();
  55. this.idle = function (callback) {
  56. this.promise = this.promise.then(callback)
  57. }
  58. }
  59. };
  60. Queue.prototype.init.prototype = Queue.prototype;