Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/**
* Normally, when using the await keyword to wait on a promise, if the promise is
* rejected then an exception will be thrown. This means that to handle a rejection
* you would need to try/catch all your await usages, which is inconvenient.
*
* This helper is meant to be used with the await keyword to wrap the promise
* so that it never throws an exception; it is guaranteed to resolve successfully.
*
* In the case of an error, it will be available in the resolved result object so
* that the caller can handle the error without a try/catch.
*
* For example, this:
*
* let data = null;
* try {
* data = await this.DataSource.retrieve();
* } catch (error) { ... }
*
* becomes this:
*
* let result = await on(this.DataSource.retrieve())
* if (err) { ... }
* let data = result.data;
*
* @param promise The promise to wait on.
* @returns A promise that ALWAYS resolves succesfully.
*/
export function on<T>(promise: Promise<T>): Promise<OnResult<T>> {
let wrappedPromise = new Promise<OnResult<T>>((resolve, reject) => {
promise.then((data: T) => {
resolve({
error: null,
data: data,
});
}).catch((error: any) => {
resolve({
error: error,
data: null,
});
});
});
return wrappedPromise;
}
export interface OnResult<T> {
error: any;
data: T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment