(no title)
tanduv | 7 months ago
async function fetchDataWithAxios() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log('Axios Data:', response.data);
} catch (error) {
console.error('Axios Error:', error);
}
}
async function fetchDataWithFetch() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) { // Check if the HTTP status is in the 200-299 range
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); // Parse the JSON response
console.log('Fetch Data:', data);
} catch (error) {
console.error('Fetch Error:', error);
}
}
Cthulhu_|7 months ago
farkin88|7 months ago
hn_throwaway_99|7 months ago
jedwards1211|7 months ago
Tokumei-no-hito|7 months ago
{ throwNotOk, parseJson }
they know that's 99% of fetch calls, i do t see why it can't be baked in.
freeopinion|7 months ago
The following seems cleaner than either of your examples. But I'm sure I've missed the point.
I share this at the risk of embarrassing myself in the hope of being educated.Cthulhu_|7 months ago
You'd probably put the code that runs the request in a utility function, so the call site would be `await myFetchFunction(params)`, as simple as it gets. Since it's hidden, there's no need for the implementation of myFetchFunction to be super clever or compact; prefer readability and don't be afraid of code length.
fmorel|7 months ago
So treating "get a response" and "get data from a response" separately works out well for us.
stevage|7 months ago
porridgeraisin|7 months ago
mythz|7 months ago
Cthulhu_|7 months ago
Code doesn't need to be concise, it needs to be clear. Especially back-end code where code size isn't as important as on the web. It's still somewhat important if you run things on a serverless platform, but it's more important then to manage your dependencies than your own LOC count.