Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xudaolong/98ad318ecb38af9abf52b23d2f1dd1fe to your computer and use it in GitHub Desktop.
Save xudaolong/98ad318ecb38af9abf52b23d2f1dd1fe to your computer and use it in GitHub Desktop.
JavaScript-Fetch 优雅使用|-|&tag=Other
import fetch from 'isomorphic-fetch';
// usage : const { status, data, error } = yield fetcher('/api/url');
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 }));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment