Cześć,
Mam pytanie dotyczące fetch. Przerabiam pewien kurs i koleś zrobił coś takiego:
class EasyHTTP {
get(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
}
const http = new EasyHTTP;
http.get('https://jsonplaceholder.typicode.com/users')
.then(data => console.log(data))
.catch(reason => console.log(Error(reason)));
Czy istnieje jakiś powód, dla którego powinno się owijać fetch w new Promise? Przecież fetch sam w sobie zwraca promise. Przerobiłem to na coś takiego i w praktyce też działa:
class EasyHTTP {
get(url) {
return fetch(url)
.then(response => response.json())
.then(data => data)
.catch(reason => Error(reason));
}
}
const http = new EasyHTTP;
http.get('https://jsonplaceholder.typicode.com/users')
.then(data => console.log(data))
.catch(reason => console.log(Error(reason)));
À propos programowania obiektowego. Czy nie lepszym rozwiązaniem byłoby tutaj wykorzystanie statycznych metod skoro klasa i tak nie ma konstruktora?