4 ms·
Slightly off topic but this code in example #5: get() { return new Promise((resolve, reject) => { fetch(`${baseAPI}/heroes`) .then(response
by scottmf 8y ago
Slightly off topic but this code in example #5:
get() {
return new Promise((resolve, reject) => {
fetch(`${baseAPI}/heroes`)
.then(response => response.json())
.then(json => resolve(json))
.catch(err => {
reject (err);
});
});
}
Why not just:
get() {
return fetch(`${baseAPI}/heroes`)
.then(response => response.json());
}
- AaronFriel 8y agoThat has fewer brackets to colorize.
- deleted 8y ago[deleted]
- deleted 8y ago[deleted]
- akerro 8y agoBy the end of a day, he reports number of lines written and committed.
- daybreaker2 8y agoBecause he needs it wrapped in a promise, sending a resolve/reject?
- glitch003 8y agoFetch and response.json() both return promises. So it's still a promise.
- Guillaume86 8y agoTrue and in this particular example for response.json() it doesn't even matter.
- robotpony 8y agoA promise is a promise ...
- azerothian 8y agoor async get() { const response = await fetch(`${baseAPI}/heroes`); return response.json(); }
- OutThisLife 8y agoor async get () { return await (await fetch(`${baseAPI}/heroes`)).json() }
- Boulth 8y agoIf you see `return await` glued together just like that you can drop the `await` as it's effectively a no-op in this case.
- rofrol 8y agoagree. I would only add rejecting when !response.ok function fetchPost(uri, body) { return new Request(uri, { method: 'POST', mode: 'cors', headers: { 'Authorization': 'token 123412341234' }, body: JSON.stringify(body) }) } function fetchStatus(response) { return response.ok ? Promise.resolve(response) : Promise.reject(new Error(response.statusText)); } fetch('https://httpstat.us/500') .then(fetchStatus) .then(function(result) { console.log(result) }) .catch(function(err) { console.log('BAD:', err) }); https://medium.com/@luminarious/i-was-trying-out-fetch-literally-this-morning-and-i-notice-you-kind-of-skipped-a-simple-solution-62a734c28dfb https://medium.com/@luminarious/i-was-trying-out-fetch-liter...