Skip to content

Instantly share code, notes, and snippets.

@carlrip
Created January 27, 2019 11:03
Show Gist options
  • Save carlrip/db358640dd83c0f6f3fb564990078d33 to your computer and use it in GitHub Desktop.
Save carlrip/db358640dd83c0f6f3fb564990078d33 to your computer and use it in GitHub Desktop.
async fetch with types handling errors
export interface IHttpResponse<T> extends Response {
parsedBody?: T;
}
export const http = <T>(request: RequestInfo): Promise<IHttpResponse<T>> => {
return new Promise((resolve, reject) => {
let response: IHttpResponse<T>;
fetch(request)
.then(res => {
response = res;
return res.json();
})
.then(body => {
if (response.ok) {
response.parsedBody = body;
resolve(response);
} else {
reject(response);
}
})
.catch(err => {
reject(err);
});
});
};
// example consuming code
let response: IHttpResponse<ITodo[]>;
try {
response = await http<ITodo[]>(
"https://jsonplaceholder.typicode.com/todosX"
);
console.log("response", response);
} catch (response) {
console.log("Error", response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment