Skip to content

Commit

Permalink
feat: rework the module.
Browse files Browse the repository at this point in the history
Now only undefined rejection is treated as 'empty value' and replaced with Error instance.

Fixed types as requested in #9 & #15 not return type is inferred from promise.

BREAKING CHANGE: now module has default export only.
  • Loading branch information
xobotyi committed Mar 4, 2020
1 parent 5b90a6c commit bf947c3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
16 changes: 7 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
export type AWAIT_OF_RETURN_TYPE = [any?, Error?];
type AwaitOfReturnType<T> = Readonly<[T | undefined, Error?]>;

export function of(promise: Promise<any>): Promise<AWAIT_OF_RETURN_TYPE> {
export default function of<T = any>(promise: Promise<T>): Promise<AwaitOfReturnType<T>> {
return Promise.resolve(promise)
.then((r: any): AWAIT_OF_RETURN_TYPE => [r])
.then((result): Readonly<[T]> => [result])
.catch(
(e: Error | undefined | null): AWAIT_OF_RETURN_TYPE => {
if (e === undefined || e === null) {
return [e, new Error('Rejection with empty value')];
(err): Readonly<[undefined, Error]> => {
if (typeof err === 'undefined') {
err = new Error('Rejection with empty value');
}

return [undefined, e];
return [undefined, err];
},
);
}

export default of;
4 changes: 2 additions & 2 deletions tests/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion,@typescript-eslint/ban-ts-ignore */
import { of } from '../src';
import of from '../src';

describe('await-of', () => {
it('should return resolve result as first array`s item', async () => {
Expand All @@ -18,7 +18,7 @@ describe('await-of', () => {
});

it('should return unhandled error as second array`s item', async () => {
const [res, err = undefined] = await of(
const [res, err] = await of(
new Promise(() => {
throw new Error('Unhandled error!');
}),
Expand Down

0 comments on commit bf947c3

Please sign in to comment.