Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active August 30, 2023 08:48
Show Gist options
  • Save smitroshin/205661a13c0226ebf1acfbae60d1e0e8 to your computer and use it in GitHub Desktop.
Save smitroshin/205661a13c0226ebf1acfbae60d1e0e8 to your computer and use it in GitHub Desktop.
Async + Await Error Handling Strategy using Axios
import { AxiosError, AxiosResponse } from "axios";
/**
* Axios types overload
*/
export function asyncHelper<ResponseType = any, ErrorType = any>(
promise: Promise<AxiosResponse<ResponseType | ErrorType, any>> | null | undefined | false
): Promise<{ response: AxiosResponse<ResponseType> | null; error: AxiosError<ErrorType> | null }>;
/**
* Async helper
*
* Usage:
*
* const { response, error } = await asyncHelper(axios.get(...));
*
* Source: https://youtu.be/wsoQ-fgaoyQ
*/
export function asyncHelper<ResponseType = any, ErrorType = any>(
promise: Promise<ResponseType | ErrorType> | null | undefined | false
) {
return promise
? Promise.allSettled([promise]).then(([res]) => ({
response: res.status === "fulfilled" ? res.value : null,
error: res.status === "rejected" ? res.reason : null,
}))
: Promise.resolve({
response: null,
error: null,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment