Skip to content

Instantly share code, notes, and snippets.

@LopatkinEvgeniy
Created September 30, 2016 14:31
Show Gist options
  • Save LopatkinEvgeniy/ecebe5c64ca9d25eadf9a9d3c51e7eaf to your computer and use it in GitHub Desktop.
Save LopatkinEvgeniy/ecebe5c64ca9d25eadf9a9d3c51e7eaf to your computer and use it in GitHub Desktop.
Unrejectable fetch
import fetch from 'isomorphic-fetch';
export default function fetcher(url, options = {}) {
return new Promise((resolve) => {
fetch(url, Object.assign({}, {
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
}, options))
.then(response => {
const status = +response.status;
response.json()
.then(data => resolve({ status, data }))
.catch(error => resolve({ status, error }));
})
.catch(error => resolve({ error }));
});
}
@LopatkinEvgeniy
Copy link
Author

Usage inside generator:

const { status, data, error } = yield fetcher('/some/url');

if (error) {
  console.log('error', error);
  return;
}

console.log('data', data)

@LopatkinEvgeniy
Copy link
Author

Go-style error handling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment