Fix bug in cancelling last task in TaskQueue

Summary:
We don't want to remove the last queue from the stack, it should just have no tasks in it.

Fixes issue reported here: https://www.facebook.com/groups/reactnativeoss/permalink/1569170356712926/

Reviewed By: yungsters

Differential Revision: D3539287

fbshipit-source-id: ea95673491fee0ea82f0f1b79b8f60e00cd3d035
This commit is contained in:
Spencer Ahrens 2016-07-11 16:06:42 -07:00 committed by Facebook Github Bot 3
parent 0a98b612aa
commit 9b184cc0f4
2 changed files with 18 additions and 6 deletions

View File

@ -15,12 +15,12 @@ const infoLog = require('infoLog');
const invariant = require('fbjs/lib/invariant');
type SimpleTask = {
name: string;
run: () => void;
name: string,
run: () => void,
};
type PromiseTask = {
name: string;
gen: () => Promise<any>;
name: string,
gen: () => Promise<any>,
};
export type Task = Function | SimpleTask | PromiseTask;
@ -75,7 +75,7 @@ class TaskQueue {
...queue,
tasks: queue.tasks.filter((task) => tasksToCancel.indexOf(task) === -1),
}))
.filter((queue) => queue.tasks.length > 0);
.filter((queue, idx) => (queue.tasks.length > 0 || idx === 0));
}
/**
@ -151,7 +151,10 @@ class TaskQueue {
DEBUG && infoLog('exec gen task ' + task.name);
task.gen()
.then(() => {
DEBUG && infoLog('onThen for gen task ' + task.name, {stackIdx, queueStackSize: this._queueStack.length});
DEBUG && infoLog(
'onThen for gen task ' + task.name,
{stackIdx, queueStackSize: this._queueStack.length},
);
this._queueStack[stackIdx].popable = true;
this.hasTasksToProcess() && this._onMoreTasks();
})

View File

@ -142,4 +142,13 @@ describe('TaskQueue', () => {
expectToBeCalledOnce(task4);
expect(taskQueue.hasTasksToProcess()).toBe(false);
});
it('should not crash when last task is cancelled', () => {
const task1 = jest.fn();
taskQueue.enqueue(task1);
taskQueue.cancelTasks([task1]);
clearTaskQueue(taskQueue);
expect(task1).not.toBeCalled();
expect(taskQueue.hasTasksToProcess()).toBe(false);
});
});