Skip to content

Instantly share code, notes, and snippets.

@mir4ef
Last active September 21, 2019 04:59
Show Gist options
  • Save mir4ef/14db21de37a6375f3f98f6caa1b4ebcc to your computer and use it in GitHub Desktop.
Save mir4ef/14db21de37a6375f3f98f6caa1b4ebcc to your computer and use it in GitHub Desktop.
async/await utility function for more elegant handling of failures rather than adding try/catch blocks everywhere. This allows us to also know what exactly failed.
interface IAsyncAwait<T, R> {
error: R|Error|null;
response: T|null;
}
// async/await utility function for more elegant handling of failures
const asyncAwaitHandler: <A, B>(promise: Promise<A>) => Promise<IAsyncAwait<A|null, B|null>> = <A, B>(promise: Promise<A>): Promise<IAsyncAwait<A|null, B|null>> => {
return promise
.then((response: A): IAsyncAwait<A, null> => ({ error: null, response }))
.catch((error: B): Promise<IAsyncAwait<null, B>> => Promise.resolve({ error, response: null }));
};
// example promise
const myPromise = (errorMe?: any): Promise<string> => {
if (errorMe) {
return Promise.reject('error occurred');
}
return Promise.resolve('success');
};
// usage of the utility function
const usage = async (shouldIThrow?: any): Promise<void> => {
const data: IAsyncAwait<string|null, any> = await asyncAwaitHandler(myPromise(shouldIThrow));
if (data.error) {
console.log(data.error);
} else {
console.log(data.response);
}
// or we can use destructuring
/**
const { error, response }: IAsyncAwait<string|null, any> = await asyncAwaitHandler(myPromise(shouldIThrow));
if (error) {
console.log(error);
} else {
console.log(response);
}
**/
};
usage(); // prints 'success'
usage('throw me'); // prints 'error occurred'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment