Skip to content

Commit

Permalink
Merge pull request #130 from t-bonatti/emit-events
Browse files Browse the repository at this point in the history
 Emit events on finished task / Execute function or promise
  • Loading branch information
merencia committed Apr 29, 2019
2 parents d1bc7f1 + 3ee23f9 commit b3da6a6
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/task.js
Expand Up @@ -5,17 +5,28 @@ const EventEmitter = require('events');
class Task extends EventEmitter{
constructor(execution){
super();
if(typeof execution !== 'function'){
if(typeof execution !== 'function') {
throw 'execution must be a function';
}
this._execution = execution;
}

this.execute = (now) => {
// TODO: Handle execution
// check if execution returns a promise
// emit events on start and on finished
// force execution return a promise
return execution(now);
};
execute(now) {
let exec;
try {
exec = this._execution(now);
} catch (error) {
return this.emit('task-failed', error);
}

if (exec instanceof Promise) {
return exec
.then(() => this.emit('task-finished'))
.catch((error) => this.emit('task-failed', error));
} else {
this.emit('task-finished');
return exec;
}
}
}

Expand Down
49 changes: 49 additions & 0 deletions test/task-test.js
@@ -0,0 +1,49 @@
const { assert } = require('chai');
const sinon = require('sinon');
const Task = require('../src/task');

describe('Task', () => {
beforeEach(() => {
this.clock = sinon.useFakeTimers(new Date(2018, 0, 1, 0, 0, 0, 0));
});

afterEach(() => {
this.clock.restore();
});

it('should emit event on finish a task', async () => {
let finished = false;
let task = new Task(() => 'ok');
task.on('task-finished', () => finished = true);
await task.execute();
assert.equal(true, finished);
});

it('should emit event on error a task', async () => {
let error;
let task = new Task(() => {
throw Error('execution error');
});
task.on('task-failed', (err) => error = err.message);
await task.execute();
assert.equal('execution error', error);
});

it('should emit event on finish a promise task', async () => {
let finished = false;
const promise = () => new Promise((resolve) => resolve('ok'));
let task = new Task(promise);
task.on('task-finished', () => finished = true);
await task.execute();
assert.equal(true, finished);
});

it('should emit event on error a promise task', async () => {
let failed = false;
const promise = () => new Promise((resolve, reject) => reject('errou'));
const task = new Task(promise);
task.on('task-failed', (error) => failed = error);
await task.execute();
assert.equal('errou', failed);
});
});

0 comments on commit b3da6a6

Please sign in to comment.