Skip to content

Commit

Permalink
Implement cancellable tasks. (#1204)
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima authored Apr 3, 2020
1 parent fcd3825 commit c2a547b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
18 changes: 17 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,11 +650,20 @@ class Generator extends EventEmitter {
self.emit(`method:${methodName}`);

runAsync(function() {
if (task.cancellable && !self._running) {
return Promise.resolve();
}

self.async = () => this.async();
self.runningState = { namespace, queueName, methodName };
return method.apply(self, self.args);
})()
.then(function() {
if (task.cancellable && !self._running) {
completed();
return;
}

delete self.runningState;
const eventName = `done$${namespace || 'unknownnamespace'}#${methodName}`;
debug(`Emiting event ${eventName}`);
Expand Down Expand Up @@ -682,6 +691,13 @@ class Generator extends EventEmitter {
);
}

/**
* Ignore cancellable tasks.
*/
cancelCancellableTasks() {
this._running = false;
}

/**
* Runs the generator, scheduling prototype methods on a run queue. Method names
* will determine the order each method is run. Methods without special names
Expand Down Expand Up @@ -729,7 +745,7 @@ class Generator extends EventEmitter {
const item = property.value ? property.value : property.get.call(self);

const priority = self._queues[name];
let taskOptions = { ...priority };
let taskOptions = { ...priority, cancellable: true };

// Name points to a function; run it!
if (typeof item === 'function') {
Expand Down
12 changes: 12 additions & 0 deletions test/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,18 @@ describe('Base', () => {
assert(fs.existsSync(this.testGen.destinationPath('foo.txt')));
});
});

it('can cancel cancellable tasks', function(done) {
this.TestGenerator.prototype.cancel = function() {
this.cancelCancellableTasks();
};

this.TestGenerator.prototype.throwing = () => {
throw new Error('not thrown');
};

this.testGen.run().then(done);
});
});

describe('#argument()', () => {
Expand Down

0 comments on commit c2a547b

Please sign in to comment.