Skip to content

Commit

Permalink
feat(then): Added first version of the then proposal
Browse files Browse the repository at this point in the history
  • Loading branch information
hrajchert committed May 22, 2019
1 parent ec3bf37 commit 366e15b
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/task/task.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,68 @@ describe('Task', () => {
);
});
});
describe('then', () => {
// TODO: copy pasted from fork, but I probably should use
// spies instead of relying on `cb`
it('should be lazy', cb => {
// GIVEN: a manually created task
const task = new Task(resolve => {
// This should be called
expect(true).toBe(true);
cb();
});

// WHEN: we fork
// THEN: the content of the task is called
task.then(x => x, x => x);
});

it('Should call success handler on success', cb => {
// GIVEN: A resolved task
const task = Task.resolve(0);

// WHEN: we fork using then
// THEN: should call its success function with the resolved value
task.then(
assertFork(cb, x => expect(x).toBe(0)),
jestAssertNever(cb)
);
});

it('Should call error handler on rejection', cb => {
// GIVEN: A rejected task
const task = Task.reject('buu');

// WHEN: we fork using then
// THEN: should call the error handler with the error when it fails
task.then(
jestAssertNever(cb),
assertFork(cb, x => expect(x).toBe('buu'))
);
});

it('Should be awaitable', async () => {
// GIVEN: A resolved task
const task = Task.resolve(0);

// WHEN: we await on it
const val = await task;

// THEN: It shoud yield the value
expect(val).toEqual(0);
});

it('Should be asynchronous', async () => {
// GIVEN: A task that resolves in the future
const task = new Task<string, never>(resolve =>
setTimeout(_ => resolve('wii'), 10)
);

// WHEN: we await on it
const val = await task;

// THEN: it should yield the value in 10ms
expect(val).toEqual('wii');
});
});
});
9 changes: 9 additions & 0 deletions src/task/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,14 @@ export class Task <T, E> {
errorFn
);
}

then <B> (successFn: (value: T) => B, errorFn: (error: any) => any): Promise<B> {
return new Promise((resolve, reject) => {
this.resolver(resolve, reject);
}).then(
(x: any) => successFn(x),
errorFn
);
}
}

0 comments on commit 366e15b

Please sign in to comment.