Skip to content

Commit

Permalink
feat(Promise): added defaultResult parameter to tryCatch
Browse files Browse the repository at this point in the history
  • Loading branch information
alisahinozcelik committed Feb 24, 2022
1 parent 25f1f20 commit 0e6850f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
7 changes: 4 additions & 3 deletions src/promise/proto/try-catch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ declare global {
*
* ```
* * * *
* @param defaultResult Setting this will put the value into the result field when the promise throws error
*/
tryCatch<E = any>(): Promise<[E, T]>;
tryCatch<E = any>(defaultResult?: T): Promise<[E, T]>;
}
}

Promise.prototype.tryCatch = function<T, E>(this: Promise<T>): Promise<[E, T]> {
return tryCatch<T, E>(this);
Promise.prototype.tryCatch = function<T, E>(this: Promise<T>, defaultResult: T = null): Promise<[E, T]> {
return tryCatch<T, E>(this, defaultResult);
};
5 changes: 3 additions & 2 deletions src/promise/try-catch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,14 @@
* ```
* * * *
* @param promise Promise to try
* @param defaultResult Setting this will put the value into the result field when the promise throws error
* @returns Error and result array
*/
export async function tryCatch<T, E = any>(promise: Promise<T>): Promise<[E, T]> {
export async function tryCatch<T, E = any>(promise: Promise<T>, defaultResult: T = null): Promise<[E, T]> {
try {
const result = await promise;
return [null, result];
} catch (error) {
return [error, null];
return [error, defaultResult];
}
}

0 comments on commit 0e6850f

Please sign in to comment.