Skip to content

Commit

Permalink
fix(toCallback): wrong handling of errors
Browse files Browse the repository at this point in the history
  • Loading branch information
yisraelx committed Mar 4, 2018
1 parent 5fa0282 commit c7f644b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
3 changes: 1 addition & 2 deletions modules/to-callback/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ function toCallback<T, R>(value: IOptionalPromise<T>, callback: (error?: any, va
.resolve(value)
.then((value) => {
return callback(null, value);
})
.catch(callback);
}, callback);
}

export default toCallback;
37 changes: 34 additions & 3 deletions test/to-callback.spec.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
import toCallback from '@promises/to-callback';

describe('toCallback', () => {
it('should be reject on callback throw error', () => {
let promise: Promise<string> = Promise.resolve<string>('foo');
return toCallback(promise, (error: any, result: string) => {
throw 'reject';
}).then(() => {
throw 'resolve';
}).catch((error: string) => {
expect(error).toBe('reject');
});
});

it('should be resolve promise from callback return', () => {
return toCallback<number, number>(0, (error: any, num: number) => {
return Promise.resolve(++num);
}).then((num: number) => {
expect(num).toBe(1);
});
});

it('should be reject promise from callback return', () => {
return toCallback<number, never>(0, (error: any, num: number) => {
return Promise.reject(++num);
}).then(() => {
throw 'resolve';
}).catch((num: number) => {
expect(num).toBe(1);
});
});

it('should be return result to callback', () => {
let promise: any = Promise.resolve<string>('foo');
let promise: Promise<string> = Promise.resolve<string>('foo');
return toCallback(promise, (error: any, result: string) => {
expect(error).toBeNull();
expect(result).toBe('foo');
});
});

it('should be return error to callback', () => {
let promise: any = Promise.reject<string>('foo');
return toCallback(promise, (error: any) => {
let promise: Promise<string> = Promise.reject<string>('foo');
return toCallback(promise, (error: string, result: any) => {
expect(error).toBe('foo');
expect(result).toBeUndefined();
});
});
});

0 comments on commit c7f644b

Please sign in to comment.