Created
January 27, 2019 11:03
-
-
Save carlrip/db358640dd83c0f6f3fb564990078d33 to your computer and use it in GitHub Desktop.
async fetch with types handling errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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