Przeglądaj źródła

TaskQueue accept multiple tasks at a time

Adam Shaw 8 lat temu
rodzic
commit
08b11fef03
2 zmienionych plików z 45 dodań i 13 usunięć
  1. 13 13
      src/common/TaskQueue.js
  2. 32 0
      tests/automated-better/util/TaskQueue.js

+ 13 - 13
src/common/TaskQueue.js

@@ -6,21 +6,22 @@ function TaskQueue() {
 
 	$.extend(this, EmitterMixin);
 
-	this.queue = function(taskFunc) {
+	this.queue = function(/* taskFunc, taskFunc... */) {
+		q.push.apply(q, arguments); // append
+
 		if (!isRunning) {
+			isRunning = true;
 			_this.trigger('start');
-			executeTaskFunc(taskFunc);
-		}
-		else {
-			q.push(taskFunc);
+
+			if (q.length) { // at least one new task added?
+				runNext();
+			}
 		}
 	};
 
-	function executeTaskFunc(taskFunc) {
-		var res;
-
-		isRunning = true;
-		res = taskFunc();
+	function runNext() { // does not check for empty q
+		var taskFunc = q.shift();
+		var res = taskFunc();
 
 		if (res && res.then) {
 			res.then(done);
@@ -30,12 +31,11 @@ function TaskQueue() {
 		}
 
 		function done() {
-			isRunning = false;
-
 			if (q.length) {
-				executeTaskFunc(q.shift());
+				runNext();
 			}
 			else {
+				isRunning = false;
 				_this.trigger('stop');
 			}
 		}

+ 32 - 0
tests/automated-better/util/TaskQueue.js

@@ -77,4 +77,36 @@ describe('TaskQueue', function() {
 			done();
 		}, 200);
 	});
+
+	it('serially executes two tasks, the first with a promise', function(done) {
+		var q = new TaskQueue();
+		var ops = [];
+
+		q.on('start', function() {
+			ops.push('start-event');
+		});
+		q.on('stop', function() {
+			ops.push('stop-event');
+		});
+
+		q.queue(function() {
+			var deferred = $.Deferred();
+
+			ops.push('start1');
+
+			setTimeout(function() {
+				ops.push('stop1');
+				deferred.resolve();
+			}, 100);
+
+			return deferred.promise();
+		}, function() {
+			ops.push('run2');
+		});
+
+		setTimeout(function() {
+			expect(ops).toEqual([ 'start-event', 'start1', 'stop1', 'run2', 'stop-event' ]);
+			done();
+		}, 200);
+	});
 });